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[0]; 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