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/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章