2013-02-13 92 views
5

我試圖給Petfinder.com打電話以獲取我們的寵物列表。網址是http://api.petfinder.com/shelter.getPets?key=xxxxx&id=CA1469&format=jsonJQuery ajax調用獲取狀態代碼0「錯誤」

該網址似乎返回的JSON罰款。但是當我嘗試撥打電話時,我收到了「錯誤」和狀態碼0.我嘗試使用jsonp,導致狀態爲200,但發生分析錯誤。如果我更改爲XML,我有狀態0和「錯誤」的結果。

$.ajax({ 

     url: "http://api.petfinder.com/shelter.getPets?key=xxxx&id=CA1469&format=json", 
     dataType: "json", 
     type: "GET", 
     success: function (data) { 
      alert("hi"); 
     }, 
     error: function (jqXHR, exception) { 
      if (jqXHR.status === 0) { 
       alert('Not connect.\n Verify Network.'); 
      } else if (jqXHR.status == 404) { 
       alert('Requested page not found. [404]'); 
      } else if (jqXHR.status == 500) { 
       alert('Internal Server Error [500].'); 
      } else if (exception === 'parsererror') { 
       alert('Requested JSON parse failed.'); 
      } else if (exception === 'timeout') { 
       alert('Time out error.'); 
      } else if (exception === 'abort') { 
       alert('Ajax request aborted.'); 
      } else { 
       alert('Uncaught Error.\n' + jqXHR.responseText); 
      } 

     } 
    }); 
+1

您的控制檯中是否出現「相同原點」錯誤?你使用IE嗎?跨域請求需要發送無論是作爲JSONP(需要適當的JSONP響應)或CORS啓用這就需要服務器支持CORS並支持CORS的瀏覽器。 jQuery的不支持CORS在IE <10 – 2013-02-13 18:56:24

+0

Trello的API客戶端庫提供的,他們如何處理CORS支持一個很好的例子:[阿賈克斯jqXHR.status的https://trello.com/1/client.coffee – forivall 2013-02-13 19:07:05

+0

可能重複== 0修復錯誤](http://stackoverflow.com/questions/23802474/ajax-jqxhr-status-0-fix-error) – 2015-07-09 11:31:42

回答

1

您正在運行到 XSS CORS問題。最好的解決方案是在您的Web服務器上設置代理,並通過它來路由AJAX調用。

+1

正如KevinB所說;我認爲你的意思是CORS,而不是XSS – Alexander 2013-02-13 19:01:55

+0

@Alexander同意。 – 2013-02-13 19:03:14

+0

我使用AWS API網關對我機應用...並獲得這個同樣的問題...你可以建議優選CORS政策,使得這個錯誤得到解決。我ryte測試它現在使用運行在body標籤的「的onload」事件一個簡單的Ajax調用 – 2016-08-16 07:39:15

2

您需要確保當服務器向您發送錯誤響應時,它還會發送適當的CORS頭文件。

如果沒有瀏覽器不會讓你的JavaScript代碼來看到任何信息來源來自該域,即使狀態正在添加的代碼。