Javascript 带有 JSON 数组的 jQuery“每个”循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3030321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery 'each' loop with JSON array
提问by Ben
I'm trying to use jQuery's eachloop to go through this JSON and add it to a divnamed #contentHere. The JSON is as follows:
我正在尝试使用 jQuery 的each循环来遍历这个 JSON 并将其添加到一个div命名的#contentHere. JSON 如下:
{ "justIn": [
{ "textId": "123", "text": "Hello", "textType": "Greeting" },
{ "textId": "514", "text":"What's up?", "textType": "Question" },
{ "textId": "122", "text":"Come over here", "textType": "Order" }
],
"recent": [
{ "textId": "1255", "text": "Hello", "textType": "Greeting" },
{ "textId": "6564", "text":"What's up?", "textType": "Question" },
{ "textId": "0192", "text":"Come over here", "textType": "Order" }
],
"old": [
{ "textId": "5213", "text": "Hello", "textType": "Greeting" },
{ "textId": "9758", "text":"What's up?", "textType": "Question" },
{ "textId": "7655", "text":"Come over here", "textType": "Order" }
]
}
I'm getting this JSON through use of this code:
我通过使用此代码获取此 JSON:
$.get("data.php", function(data){
})
Any solutions?
任何解决方案?
回答by karim79
Try (untested):
尝试(未经测试):
$.getJSON("data.php", function(data){
$.each(data.justIn, function() {
$.each(this, function(k, v) {
alert(k + ' ' + v);
});
});
$.each(data.recent, function() {
$.each(this, function(k, v) {
alert(k + ' ' + v);
});
});
$.each(data.old, function() {
$.each(this, function(k, v) {
alert(k + ' ' + v);
});
});
});
I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:
我想,三个独立的循环,因为您可能希望以不同的方式对待每个数据集(justIn、recent、old)。如果没有,你可以这样做:
$.getJSON("data.php", function(data){
$.each(data, function(k, v) {
alert(k + ' ' + v);
$.each(v, function(k1, v1) {
alert(k1 + ' ' + v1);
});
});
});
回答by John K
Brief code but full-featured
代码简短但功能齐全
The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.
下面是一个混合 jQuery 解决方案,它将每个数据“记录”格式化为一个 HTML 元素,并将数据的属性用作 HTML 属性值。
The jquery eachruns the inner loop; I needed the regular JavaScript foron the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.
jqueryeach运行内循环;我需要for外循环上的常规 JavaScript才能获取属性名称(而不是值)以显示为标题。根据口味,它可以修改为略有不同的行为。
This is only 5 main lines of codebut wrapped onto multiple lines for display:
这只是 5 行主要代码,但包装成多行以供显示:
$.get("data.php", function(data){
for (var propTitle in data) {
$('<div></div>')
.addClass('heading')
.insertBefore('#contentHere')
.text(propTitle);
$(data[propTitle]).each(function(iRec, oRec) {
$('<div></div>')
.addClass(oRec.textType)
.attr('id', 'T'+oRec.textId)
.insertBefore('#contentHere')
.text(oRec.text);
});
}
});
Produces the output
产生输出
(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")
(注意:我通过添加一个数字来修改 JSON 数据文本值,以确保我以正确的顺序显示正确的记录 - 在“调试”时)
<div class="heading">
justIn
</div>
<div id="T123" class="Greeting">
1Hello
</div>
<div id="T514" class="Question">
1What's up?
</div>
<div id="T122" class="Order">
1Come over here
</div>
<div class="heading">
recent
</div>
<div id="T1255" class="Greeting">
2Hello
</div>
<div id="T6564" class="Question">
2What's up?
</div>
<div id="T0192" class="Order">
2Come over here
</div>
<div class="heading">
old
</div>
<div id="T5213" class="Greeting">
3Hello
</div>
<div id="T9758" class="Question">
3What's up?
</div>
<div id="T7655" class="Order">
3Come over here
</div>
<div id="contentHere"></div>
Apply a style sheet
应用样式表
<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>
to get a "beautiful" looking set of data
获得一组“漂亮”的数据
More Info
The JSON data was used in the following way:
更多信息
JSON 数据的使用方式如下:
for each category (key name the array is held under):
对于每个类别(数组所在的键名):
- the key name is used as the section heading (e.g. justIn)
- 键名用作部分标题(例如justIn)
for each object held inside an array:
对于保存在数组中的每个对象:
- 'text' becomes the content of a div
- 'textType' becomes the class of the div (hooked into a style sheet)
- 'textId' becomes the id of the div
- e.g. <div id="T122" class="Order">Come over here</div>
- 'text' 成为 div 的内容
- 'textType' 成为 div 的类(挂钩到样式表中)
- 'textId' 成为 div 的 id
- 例如<div id="T122" class="Order">过来这里</div>
回答by artlung
This works for me:
这对我有用:
$.get("data.php", function(data){
var expected = ['justIn', 'recent', 'old'];
var outString = '';
$.each(expected, function(i, val){
var contentArray = data[val];
outString += '<ul><li><b>' + val + '</b>: ';
$.each(contentArray, function(i1, val2){
var textID = val2.textId;
var text = val2.text;
var textType = val2.textType;
outString += '<br />('+textID+') '+'<i>'+text+'</i> '+textType;
});
outString += '</li></ul>';
});
$('#contentHere').append(outString);
}, 'json');
This produces this output:
这会产生以下输出:
<div id="contentHere"><ul>
<li><b>justIn</b>:
<br />
(123) <i>Hello</i> Greeting<br>
(514) <i>What's up?</i> Question<br>
(122) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>recent</b>:
<br />
(1255) <i>Hello</i> Greeting<br>
(6564) <i>What's up?</i> Question<br>
(0192) <i>Come over here</i> Order</li>
</ul><ul>
<li><b>old</b>:
<br />
(5213) <i>Hello</i> Greeting<br>
(9758) <i>What's up?</i> Question<br>
(7655) <i>Come over here</i> Order</li>
</ul></div>
And looks like this:
看起来像这样:
- justIn:
(123) HelloGreeting
(514) What's up?Question
(122) Come over hereOrder
- justIn:
(123)你好问候
(514)怎么了?问题
(122)过来点菜
- recent:
(1255) HelloGreeting
(6564) What's up?Question
(0192) Come over hereOrder
- 最近:
(1255) HelloGreeting
(6564)怎么了?问题
(0192)过来点单
- old:
(5213) HelloGreeting
(9758) What's up?Question
(7655) Come over hereOrder
- old:
(5213) HelloGreeting
(9758)怎么了?问题
(7655)过来这里订购
Also, remember to set the contentTypeas 'json'
另外,记得设置contentType为'json'
回答by Florian Mertens
My solutions in one of my own sites, with a table:
我在我自己的网站之一中的解决方案,附有一张表格:
$.getJSON("sections/view_numbers_update.php", function(data) {
$.each(data, function(index, objNumber) {
$('#tr_' + objNumber.intID).find("td").eq(3).html(objNumber.datLastCalled);
$('#tr_' + objNumber.intID).find("td").eq(4).html(objNumber.strStatus);
$('#tr_' + objNumber.intID).find("td").eq(5).html(objNumber.intDuration);
$('#tr_' + objNumber.intID).find("td").eq(6).html(objNumber.blnWasHuman);
});
});
sections/view_numbers_update.php Returns something like:
Sections/view_numbers_update.php 返回如下内容:
[{"intID":"19","datLastCalled":"Thu, 10 Jan 13 08:52:20 +0000","strStatus":"Completed","intDuration":"0:04 secs","blnWasHuman":"Yes","datModified":1357807940},
{"intID":"22","datLastCalled":"Thu, 10 Jan 13 08:54:43 +0000","strStatus":"Completed","intDuration":"0:00 secs","blnWasHuman":"Yes","datModified":1357808079}]
HTML table:
HTML表格:
<table id="table_numbers">
<tr>
<th>[...]</th>
<th>[...]</th>
<th>[...]</th>
<th>Last Call</th>
<th>Status</th>
<th>Duration</th>
<th>Human?</th>
<th>[...]</th>
</tr>
<tr id="tr_123456">
[...]
</tr>
</table>
This essentially gives every row a unique id preceding with 'tr_' to allow for other numbered element ids, at server script time. The jQuery script then just gets this TR_[id] element, and fills the correct indexed cell with the json return.
这基本上为每一行提供了一个唯一的 id,前面带有 'tr_' 以允许在服务器脚本时使用其他编号的元素 id。jQuery 脚本然后只获取这个 TR_[id] 元素,并用 json 返回填充正确的索引单元格。
The advantage is you could get the complete array from the DB, and either foreach($array as $record) to create the table html, OR (if there is an update request) you can die(json_encode($array)) before displaying the table, all in the same page, but same display code.
优点是你可以从数据库中获取完整的数组,或者 foreach($array as $record) 创建表 html,或者(如果有更新请求)你可以在显示之前死(json_encode($array))表,都在同一页中,但显示代码相同。


