1. 程式人生 > WINDOWS開發 >webApi前端ajax呼叫後端返回{"readyState":0,"status":0,"statusText":"error"}解決方案

webApi前端ajax呼叫後端返回{"readyState":0,"status":0,"statusText":"error"}解決方案

 var url = data.url,params = data.params,try_times = data.try_times,async = data.sync == ‘false‘ ? false : true;      

        $.ajax({
            url: url,type: "POST",timeout: 60000,async: async,data: JSON.stringify(params),dataType: "text",success: function (data) {
                alert("aaaa+bbb");                
},error: function (error) {//增加訪問出錯資訊返回 alert("出錯了" + JSON.stringify(error)); },complete: function (XMLHttpRequest,status) {
} });

前端報錯為:{"readyState":0,"status":0,"statusText":"error"},這個問題主要是由於跨域引起的

解決方案如下:

在請求的服務端的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>