2013-01-09 48 views
0

我試圖解析來自AJAX調用JSON的結果,但做服務器的,我只能得到一個大字符串的限制。有返回幾個元素,但我需要消耗數據都扔進一個元素。現在這裏是棘手的事情...如果我使用螢火蟲響應有一個JSON標籤,一切看起來像一個正確的JSON對象,但是當我嘗試映射或查看使用警報的結果時,我注意到他們是單引號而不是雙引號引號。我試過將引號替換爲無效。在這一點上我非常難過。我無法解析一個jQuery AJAX JSON響應

the alert would print out something simular to this: [{'id':'2663','parent':'2663'},{'id':'2664','parent':'2664'},] 

     $.ajax({ 
      url: myURL, 
      type: 'GET', 
      dataType: "json", 
      complete: function(docData) { 
       var docResults = docData.responseText; 
       alert(docResults); 
       $(docResults).each(function(i,val){ 
        $.each(val,function(k,v){ 
          console.log(k+" : "+ v);  
        }); 
       });     
      } 
     }); 
+0

你的服務器返回無效JSON。 – Pointy

+0

好了,不要發佈客戶端腳本,後返回,而不是性反應,你的服務器腳本... – shaddy

+0

有一個_evil_的解決方案。 –

回答

2

解決此問題的正確方法是修復它在服務器上,但是,有一種方法可以使用dataFilter回調修復它的客戶端。

$.ajax({ 
    url: myURL, 
    type: 'GET', 
    dataType: "json", 
    dataFilter: function(response) { 

    // *** Note: this will have to be modified if quotes 
    // *** can be contained within the data. It doesn't appear as though 
    // *** that is the case with the data you have provided. 

    return response 
     // fix trailing comma 
     .replace("},]","}]") 
     // fix quotes 
     .replace(/'/g,'"')); 
    }, 
    success: function (response) { 
    $.each(response,function(){ 
     console.log(this); 
    }); 
    } 
});