zoukankan      html  css  js  c++  java
  • ASP.NET环境下XMLHttpRequest中responseText()方法返回值为空问题讨论

    ASP.NET环境下XMLHttpRequest中responseText()方法返回值为空问题讨论

    一、问题产生环境:用JavaScriptXMLHttpRequest发送GET请求,请求的数据来自asp.net接口,数据格式为stringjson

    代码如下:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
    <head>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <title></title>
        <script src="js/jquery-1.4.2.js" type="text/javascript"></script>
        <script type="text/javascript">
            function btn_click() {
            var xmlHttp = new XMLHttpRequest();
            if(!xmlHttp){
                alert("error from create xmlHttp!");
                return;
            }
            //配置XMLHttpRequest对象
            xmlHttp.open("GET", "http://192.168.1.102:8030/get.aspx",true);
            //设置回调函数
            xmlHttp.onreadystatechange = function () {
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                    document.getElementById("result").innerHTML = xmlHttp.responseText;
                }
            }
            //发送请求
            xmlHttp.send(null);
        }
        </script>
    </head>
    <body>
        <input type="button" value="获取系统当前时间" id="btn" onclick="btn_click();" />
        <div id="result">
        </div>
    </body>
    </html>

    二、分析

    1.如果将asp.net接口已本地调试的方法给出,那么xmlHttp.status的值将为0

    2.通过调试,xmlHttp.responseText的返回值为空的原因与接口给出的数据格式无关;

    3.最终发现是跨域问题。

    三、解决方法:

    在配置文件中(Web.config)加入以下代码已解决跨域问题:

    <system.webServer>
       <httpProtocol>
          <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Headers" value="Content-Type" />
          <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
          </customHeaders>
       </httpProtocol> 
    </system.webServer>

    查看原文:http://www.cnblogs.com/zhangtingzu/

  • 相关阅读:
    【转】ubuntu 13.04 普通用户丢失sudo权限后的恢复办法
    #流水账# Mac上用Virtualbox安装//配置虚拟机Ubuntu
    #小知识# 网页内容居中的办法
    无法正常访问FTP服务(Windows 7 + VirtualBox + Ubuntu + vsftpd)
    【转】WordPress上传主题出错:无法创建目录
    判断是PC端还是移动端
    公告滚动
    vs code 汉化 自动保存 插件
    手机端的适配
    css 常见属性
  • 原文地址:https://www.cnblogs.com/zhangtingzu/p/7042353.html
Copyright © 2011-2022 走看看