Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' heade

时间:2021-02-25 04:27:29

XMLHttpRequest cannot load http://10.164.153.37:8050/WebService/WebService.asmx/wsGetStreetData.

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' heade

使用Ajax 远程 post 到WebService页面的wsGetStreetData方法。报以上错误。

jquery ajax跨域请求,webservice webconfig配置

前台代码:

// 街道的数据
function getStreetData() {
var time1 = $('#time1_street').val(); if (time1 == "" || time1 == null) { alert("请输入值~"); return false; }
var time2 = $('#time2_street').val(); if (time2 == "" || time2 == null) { alert("请输入值~"); return false; }
var data = {
time1: time1,
time2: time2
};
data = JSON.stringify(data);
$.ajax({
type: "post",
url: 'http://10.164.153.37:8050/WebService/WebService.asmx/wsGetStreetData',
async: true,
datatype: "JSONP",
jsonpCallback: "jsonpcallback",
contentType: "application/json",
data: data,
success: function (response) {
var d; d = JSON.parse(response.d);
var jsonData = JSON.stringify(d);
jsonData = jsonData
.replaceAll('"PROJECT_ID":', '')
.replaceAll('"REGION_NAME":', '')
.replaceAll('"TAX":', '')
.replaceAll('"QJSR":', '')
.replaceAll('{', '[')
.replaceAll('}', ']');
jsonData = jsonData.substring(1, jsonData.length - 1);
$('#txtRegionData').val('["id", "街乡", "纳税总额", "区级收入"],' + jsonData);
}
});
}

后台代码:

   [WebMethod]
public string wsGetStreetData(string time1, string time2)
{
StringBuilder strsql = new StringBuilder();
strsql.AppendFormat(@"", time1, time2);
DataTable dt = OracleHelper.Query(strsql.ToString()).Tables[]; return JsonConvert.SerializeObject(dt);
}

解决方案:在服务器端的Web.config文件中添加一下内容。

 <system.web>
<!--提供Web服务访问方式-->
<webServices>
<protocols>
<add name="HttpSoap"/>
<add name="HttpPost"/>
<add name="HttpGet"/>
<add name="Documentation"/>
</protocols>
</webServices>
</system.web>
 <configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
<modules>
<add name="MyHttpModule" type="WebServiceDemo.MyHttpModule"/>
</modules>
</system.webServer>
</configuration>

如果报错:

未能加载类型“WebServiceDemo.MyHttpModule”。去掉

  <modules>
<add name="MyHttpModule" type="WebServiceDemo.MyHttpModule"/>
</modules>
即可。

如果想选定的网站可能跨域访问,修改配置如下:

<add name="Access-Control-Allow-Origin" value="http://domain1.com, http://domain2.com" />  

用的时候要注意,这样用可能有风险,具体什么风险还不清楚!!!

此文参考:http://blog.csdn.net/liyifei21/article/details/17509735