您的位置:首页 > 理论基础 > 计算机网络

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

2017-06-18 00:25 671 查看
ASP.NET环境下XMLHttpRequest中responseText()方法返回值为空问题讨论

一、问题产生环境:用JavaScript的XMLHttpRequest发送GET请求,请求的数据来自asp.net接口,数据格式为string或json。

代码如下:

<!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/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐