我有一个 JSON 数据包,它不仅仅是“数据”——还有一些与之相关的元数据——但我似乎无法引用它......
这是它的样子(JSON)
{ "count":"4",
"companies": [
{ "id":"1", "company":"Acme", "address":"1234 street st.", "city":"New York", "state":"NY", "zip":"02123", "phone":"212-222-2222", "contact":"Billy Bob", "email":"bb@ny.com", "jobscurrent":"12", "jobsdone":"11" },
{ "id":"3", "company":"Acme", "address":"1234 street st.", "city":"New York", "state":"NY", "zip":"02123", "phone":"212-222-2222", "contact":"Billy Bob", "email":"bb@ny.com", "jobscurrent":"12", "jobsdone":"11" },
{ "id":"4", "company":"Acme", "address":"1234 street st.", "city":"New York", "state":"NY", "zip":"02123", "phone":"212-222-2222", "contact":"Billy Bob", "email":"bb@ny.com", "jobscurrent":"12", "jobsdone":"11" },
{ "id":"5", "company":"Acme", "address":"1234 street st.", "city":"New York", "state":"NY", "zip":"02123", "phone":"212-222-2222", "contact":"Billy Bob", "email":"bb@ny.com", "jobscurrent":"12", "jobsdone":"11" }
] }
这是我的 jQuery 的样子......嵌套的“每个” - 第一个(这是我的理解)循环 {count,companies} 和嵌套在里面的一个循环遍历客户数组中的每个数组......
第二个工作正常(即使我没有将它嵌套在第一个内也工作正常 - 但是我需要传回类似“显示 n 条记录”之类的东西 - 但现在,“value.count”
items.push('<tr class=""><td colspan="11">' + value.count + '</td></tr>' );
返回“未定义”
啊!- 我刚刚注意到它给了我两次输出......我猜这是可以预料的 - 每次外部循环迭代一次 - 因为我有 2 个元素
所以问题是 - 我怎样才能引用我的元数据一次......显然我不想为此使用 EACH ......
我只尝试了“data.count”来引用它——但我什么也没得到,这就是为什么我采用“EACH”方式来提取 JSON 变量......
function loadTable() {
$.ajax({
type: 'POST',
url: 'company_list.php',
dataType: 'json',
success: function ( data ) {
var items = [];
var line = 1;
$.each( data, function ( key, value ) {
// meta data
items.push('<tr class=""><td colspan="11">' + value.count + '</td></tr>' );
// the real data
$.each( data.companies, function ( key, value ) {
var thisRowClass = 'odd';
if ( line % 2 ) {
thisRowClass = 'even';
}
items.push('<tr class="' + thisRowClass + '"><td>' + value.company +
'</td><td>' + value.address +
'</td><td>' + value.city +
'</td><td>' + value.state +
'</td><td>' + value.zip +
'</td><td>' + value.phone +
'</td><td>' + value.contact +
'</td><td>' + value.email +
'</td><td>' + value.jobscurrent +
'</td><td>' + value.jobsdone +
'</td><td> edit | delete ' +
'</td></tr>');
line++;
});
});
//$( '#message' ).html( '<p>Displaying' + value.count + '</p>' );
$( '#companies-list' ).append( items.join('') );
},
error: function () {
// there's an error
$( '#message' ).html( '<p>There was a problem on the server... </p>' );
}
});
}