JavaScript的:
function loadDoc(url) {
$.ajax({
url: 'mytestjson',
dataType: 'json',
cache: false
}).success(function (result) {
console.log(result);
//var txt = result.newBranches[0].newNonBranchLocation;
$.each(result.newBranches, function(index, txt)
{
// change this to FALSE when ready
if (newNonBranchLocation.indexOf('TRUE') > -1) {
$('#btbumpin').hide();
}
else {
$('#btbumpin').show();
}
});
})
}
JSON:
{
"errorNode": {
"errorCode": 0,
"errorMsg": "",
"errorSev": ""
},
"newBranches": [{
"cn": "11111101",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}, {
"cn": "11111102",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}, {
"cn": "11111103",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}, {
"cn": "11111181",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}]
}
我有上面的jQuery和JSON。我想返回newBranches
中的所有值,但我目前只获取第一个newBranches
对象的值
"cn": "11111101",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
我想返回11111101TRUE11111111111102TRUE111111
等等
即返回与newBranches
中的所有值连接的字符串。
答案 0 :(得分:2)
您可以使用双$.Each()
来交叉JSON并将值添加到缓冲区。
$(function() {
var json = {
"errorNode": {
"errorCode": 0,
"errorMsg": "",
"errorSev": ""
},
"newBranches": [{
"cn": "11111101",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}, {
"cn": "11111102",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}, {
"cn": "11111103",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}, {
"cn": "11111181",
"newNonBranchLocation": "TRUE",
"newBranchNumber": "111111"
}]};
$('body').append(dumpContentOfJSON(json.newBranches));
});
function dumpContentOfJSON(json) {
var buffer = '';
$.each(json, function(index, array)
{
buffer += dumpArray(array);
});
return buffer;
}
function dumpArray(array) {
var buffer = '';
$.each(array, function(index,value){
buffer += value;
});
return buffer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>
答案 1 :(得分:1)
在循环外声明一个变量,对于ex
var output = '';
在循环内部,您只需将所需的所有值附加到变量中即可。
output + = txt.cn + txt.newNonBranchLocation + txt.newBranchNumber;
循环完成后,您可以使用此变量,该变量将包含附加的字符串。