2013-05-05 15 views
3

好吧,我試圖從一個URL中獲取JSON文件,並使用以下jQuery代碼。使用.ajax()獲取JSON的未知錯誤

$.ajax({ 
    url: 'http://example.com/example.json', 
    dataType: 'json', 
    type: 'GET', 
    async: true, 
    cache: true, 
    crossDomain: true 
}); 

但是,當請求觸發時,Firebug表明發生了錯誤,但沒有告訴我它是什麼。

我可以在我的瀏覽器中訪問URL,沒有任何問題,JSON完全有效(根據http://www.freeformatter.com/json-validator.html)。

有什麼建議嗎?

編輯:

好吧,改變contentTypejsonp已經得到我了一步。我的JSON看起來像這樣(http://pastebin.com/hSAP30zv),但Firebug的說:

SyntaxError: invalid label 
"item" : { 
^ 

任何建議?

+0

測試其對鉻和檢查控制檯,也許錯誤信息將更加準確。 – 2013-05-05 10:15:41

+0

你希望如何實現'crossDomain'?如果您希望使用JSONP,則需要發出JSONP響應而不是JSON。如果你使用的是CORS,你應該通過'xhrFields:{withCredentials:true}'而不是(http://api.jquery.com/jQuery.ajax/) – Matt 2013-05-05 10:20:44

+1

我不確定'dataType:'json' '和'crossDomain:true'一起工作。如果您希望在**相同的**域上強制執行**跨域行爲,則只需要使用'crossDomain:true'。所以,我假設你真的做出了一個跨域請求,它返回JSON。這不會工作,除非服務器支持CORS。或者它必須返回JSONP,並且必須告訴jQuery期望帶有'dataType:'jsonp'的JSONP。 – 2013-05-05 10:21:16

回答

0

嘗試處理功能的錯誤失敗:

$.ajax({ 
    url: 'http://example.com/example.json', 
    dataType: 'json', 
    type: 'GET', 
    async: true, 
    cache: true, 
    crossDomain: true 
}).fail(function(jqXHR, textStatus) { 
    alert("Request failed: " + textStatus); 
}); 
3

此錯誤處理程序,可以幫助你:

$.ajax({ 
    url: 'http://example.com/example.json', 
    dataType: 'json', 
    type: 'GET', 
    async: true, 
    cache: true, 
    success: function (html) { 
     alert('successful : ' + html); 
    }, 
    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); 
     } 
    }, 
    crossDomain: true 
}); 
+0

是的,現在陷入'parseerror'。 – 1vasari 2013-05-05 10:36:23