2017-04-25 108 views
1

我有一個遠程頁面,看起來像這樣一個JSON輸出:AJAX JSON響應是'未定義'?

{"success":true,"content":"some texts goes here, blah blah blha"} 

我需要從JSON的content以上。

所以我這樣做:

var poutput = $('.legalP'); 

    $.ajax({ 
    url: 'http://www.url-to-page.com', 
     dataType: 'json', 
     timeout: 5000, 
     success: function(data){ 
      $.each(data, function(pi,item){ 
       var products = ''+item.content+''; 
       alert(products);  
       console.log(products); 
       poutput.append(products);     
      }); 
     }, 
     error: function(){ 
      //alert('There was an error loading the data.'); 
     } 
}); 

當我運行上面的代碼,我得到了一個未定義的alert(products);

可能有人請告知呢?

+0

註銷數據,讓我知道什麼是返回, - 感謝:

所以,你可以這樣做。 –

+0

你爲什麼使用[$ .each](http://api.jquery.com/jquery.each/)? –

回答

2

如果JSON返回結果與上面完全相同,則不需要對來自AJAX調用的響應使用$ .each迭代器。

您可以直接訪問「內容」值,因爲響應是JSON對象。在回調的第一行

success: function(data){ 
      var products = data.content; 
      alert(products); 
      ... 
     }