2010-03-27 167 views
2

我最近發佈了另一個問題,用戶直接指出我正確的方向。循環瀏覽JSON數組

$.ajax({ 
     type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000, 
     success: function(html){ 
      auth(html); 
      var JSON_array = eval(html); 
      alert(JSON_array[0].username); 
     }       
    }); 

這個正確返回數據,但我想執行一個樣「的foreach」的。該陣列包含有關多個傳入和傳出即時消息的數據。因此,如果用戶正在同時與多個人通話,則需要循環。該數組的結構如下。

Array 
(

    [0] => Array 
     (
      [username] => Emmalene 
      [contents] => 
          <ul><li class="name">ACTwebDesigns</li><li class="speech">helllllllo</li></ul> 
          <ul><li class="name">ACTwebDesigns</li><li class="speech">sds</li></ul> 
          <ul><li class="name">ACTwebDesigns</li><li class="speech">Sponge</li><li class="speech">dick</li></ul> 
          <ul><li class="name">ACTwebDesigns</li><li class="speech">arghh</li></ul> 
     ) 

) 

任何幫助非常感謝。

回答

5

嘛,因爲你是使用jQuery已經可以使用了each功能:

$.ajax({ 
     type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000, 
     success: function(html){ 
      auth(html); 
      var JSON_array = eval(html); 
      $.each(JSON_array, function(index, data) { 
       $('someelement').append(data.contents); 
      }); 
     }       
    }); 
2

相反的評價HTML,你甚至可以指定JSON作爲返回類型...

迭代時易使用$.each

$.ajax({ 
    type: "POST", 
    data: ..., 
    url: url, 
    dataType: "json", 
    success: function(data) { 
     $.each(data, function(i, item){ 
      // do something with every item in data 
      // you can reference items in data via 
      // data.fieldName 
     }); 
    } 
}); 

for ... in循環不是更難:

$.ajax({ 
    ..., 
    dataType: "json", 
    success: function(data) { 
     var fields = data.fieldName; 
     var value; 
     for (value in fields) { 
      // do something with value 
     } 
    } 
}); 
+0

不斷變得不明確 – 2010-03-27 16:08:46

+0

究竟是在哪一點? JSON是否作爲返回類型工作?你有'console.log''ed數據嗎? – Leo 2010-03-27 16:09:36

1

只是爲了澄清,正如我已經讀了很多有用的提示和答案,我只有這一個工作:

$.ajax({ 
    type: 'POST', url: './', data: 'token=' + token + '&re=8', cache: false, timeout: 5000, datatype: 'json', 
    success: function(html){ 
     auth(html); 
     var JSON_array = eval(html); 
     $.each(JSON_array, function(index, data) { 
      var talk_to = JSON_array.username; 
      var contents_to_update = JSON_array.contents; 
     }); 
    }       
}); 

這裏面做的工作:

1)使用eval。 2)數據類型:'json' 3)使用jquery的$ .each函數

+0

試驗和錯誤編程?我不明白爲什麼eval應該是必要的,如果你返回適當的JSON ... – Leo 2010-03-27 16:19:30

+0

非常多。我已經看到json的例子,他們使用eval,所以我試過,它的工作! – 2010-03-27 16:30:09