[英]looping through JSON array
I have recently posted another question which straight away users pointed me in the right direction.我最近发布了另一个问题,用户立即为我指出了正确的方向。
$.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);
}
});
this returns the data correctly but I want to perform a kind of 'foreach'.这会正确返回数据,但我想执行一种“foreach”。 the array contains data about multiple incoming and outgoing Instant Messages.
该数组包含有关多个传入和传出即时消息的数据。 So if a user is talking to more than one person at a time i need to loop through.
因此,如果用户一次与多个人交谈,我需要遍历。 the array's structure is as follows.
数组的结构如下。
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>
)
)
Any help very much appreciated.非常感谢任何帮助。
Well since you are using jQuery already you could use the each function:好吧,既然你已经在使用 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);
});
}
});
Instead of evaluating the HTML, you can even specify JSON as return type...您甚至可以将 JSON 指定为返回类型,而不是评估 HTML...
Iteration is easy when using $.each
:使用
$.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
});
}
});
But a for ... in
loop isn't much harder:但是
for ... in
循环并不难:
$.ajax({
...,
dataType: "json",
success: function(data) {
var fields = data.fieldName;
var value;
for (value in fields) {
// do something with value
}
}
});
Just to clarify, As I've read many helpful hints and answers and only this one worked for me:只是为了澄清,因为我已经阅读了许多有用的提示和答案,只有这个对我有用:
$.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;
});
}
});
this which made work:这使工作:
1) use of eval. 1) 使用评估。 2) datatype: 'json' 3) use of jquery's $.each function
2) 数据类型:'json' 3) 使用 jquery 的 $.each 函数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.