2012-11-23 124 views
6

的jQuery:jQuery的AJAX狀態 「200 OK」,但沒有數據響應

$.ajax({ 
url : url, 
type : 'GET', 
dataType: 'json', 
data: { 
    'FN' : 'GetPages', 
    'PIN' : '7659' 
}, 
xhrFields: { 
    withCredentials: true 
}, 
crossDomain: true, 
success: function(data) { 
    alert('succsess'); 
    console.log('data', data); 
}, 
error: function (xhr, ajaxOptions, thrownError) { 
    alert('error'); 
    console.log(xhr.status); 
    console.log(thrownError); 
} 
}); 

螢火蟲的Firefox網絡

Firebug Error http://s14.directupload.net/images/121123/8ar5vljg.png

會發生什麼

的AJAX 「錯誤:」事件得到t riggered我的console.log輸出:

xhr.status -> 0

thrownError -> (empty String)

這是正常的嗎?當我在瀏覽器中鍵入URL時,我收到一個帶有JSON內容的文件下載,這不應該是個問題嗎?

+0

在瀏覽器url上,響應是: [{「pg」:0,「descr」:「PC1」},{「pg」:1,「descr」:「PC2」},{「 PG 「:2」,DESCR 「:」 PC3 「},{」 PG 「:3」,DESCR 「:」 HG1 「},{」 PG 「:4」,DESCR 「:」 HG2 「},{」 PG」 :5, 「DESCR」: 「HG3」},{ 「PG」:6, 「DESCR」: 「HG4」},{ 「PG」:7, 「DESCR」: 「DW1」},{ 「PG」:8 ,「descr」:「DW2」},{「pg」:9,「descr」:「CMN」}] – user1841515

+0

另外我的理解是** jsonp **不會工作原因我不允許改變任何東西服務器和它的響應將保持json格式,而不是jsonp格式 – user1841515

+0

jsonp不會影響服務器。但它可以幫助解決CORS問題。這可能是你唯一的選擇,無需修改服務器 – JonWells

回答

10

感謝@CrimsonChin我知道它是一種同源策略問題

In computing, the same origin policy is an important security concept for a number of browser-side programming languages, such as JavaScript. The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.[1]

(從http://en.wikipedia.org/wiki/Same_origin_policy

授予JavaScript客戶端,以你的資源只需要添加一個HTTP響應頭,即基本訪問:

Access-Control-Allow-Origin: * 
Access-Control-Allow-Origin: http://foo.example.com 

(從http://enable-cors.org/

Ofc將JSON響應轉換爲JSONP響應也可以。 Thx @djakapm

2

我不能從圖像想通了,但如果你想發送AJAX請求到不同的領域,你需要使用JSONP,簡單的AJAX請求不會得到足夠的

嘗試改變dataType: 'json'dataType: 'jsonp'

,並添加callback=?URL

+0

好吧,我試了一下,我收到以下錯誤: \t 語法錯誤 descr「:」DW1「},{」pg「:8,」descr「:」DW2「},{」pg「:9, 「descr」:「CMN」}] – user1841515

+0

錯誤:jQuery172046435253250156217_1353659110552未被調用 – user1841515

+0

您是否有對服務器響應的控制?在php中,我通常會給出如下響應:$ _GET ['callback']。'()'。它會模仿一個JavaScript函數調用 – djakapm

3

試試這個

$.ajax({ type : "GET", 
      url : URL, 
      data: { 
      'FN' : 'GetPages', 
      'PIN' : '7659' 
      }, 
      xhrFields: { 
      withCredentials: true 
      }, 
      crossDomain: true, 
      dataType : "jsonp", 
      jsonp : "jsoncallback", 
      jsonpCallback : "SMS", 
      cache : true, 
       success : function(service_data) { 


         }, 
       error : function(msg) { 
       alert(JSON.stringify(msg)); 
       } 
      }); 
+0

我運行此代碼並得到以下警告框: { 「readyState的」:4 「狀態」:200, 「狀態文本」: 「成功」} 而在螢火控制檯一個錯誤: 語法錯誤:在** JSON非法字符 **響應 「DESCR」 :「CMN」}] < - 以及指向那個不應該在那裏的Questionmark的箭頭!? – user1841515

+0

@ user1841515嘗試通過json lint(http://jsonlint.com/)運行service_data以確保json格式良好 – JonWells

+0

@CrimsonChin我複製了json並運行了一次檢查 - >有效的JSON – user1841515

相關問題