標籤:網站 行修改 javascrip 節點 request fun head rip 通過
通過伺服器端設定解決前端AJAX請求跨域訪問WebServie(C#開發,IIS發布)
問題:前端通過ajax調用時候發生錯誤跨域訪問的錯誤
<!--功能說明:Ajax調用WebService
<script type="text/javascript">
function test(){
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "http://www.xxxx.org/test.asmx/TestMethod",
data:"{a:12345,b:‘abcd‘}",
success: function (response) {
alert("成功:" + response.d);
},
error: function (msg) {
alert("錯誤:" + msg);
}
})
}
</script>
解決方案:在WebService服務組態檔web.config檔案中添加跨域訪問許可,共有2個地方需要修改
1、在configuration節點中的system.web節點裡面添加
<!--客服端跨域調用要使用-->
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
表示可以支援Http的get和post訪問,可以更具需求進行修改
2、在在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>
</system.webServer>
其中Access-Control-Allow-Origin的值可以依據具體情況進行設定,為“*”表示所有網站都可以訪問
通過伺服器端設定解決前端AJAX請求跨域訪問WebServie(C#開發,IIS發布)