1
我想將列表2的數據[]
添加到列表1作爲子項。期望的輸出是列表3.但是用我的代碼,我得到空字符串作爲孩子的值。在_getJsonObject(id,user)
API調用帶來清單2.如何將數據對象添加到JSON對象?
我長相的代碼如下:
var strList = function(){
var listItems= "";
$.ajax({
url: 'http://localhost:8088/api/v1/ui/performance/custom_link_groups?',
dataType: 'json',
async: false,
success: function(data){
for (var i = 0; i < data.data.length; i++){
data.data[i].children = _getJsonObject(data.data[i].$ID,data.data[i].$userId);
}
listItems = data;
}
});
return listItems;
}();
function _getJsonObject(id,user){
var rdata = "";
$.ajax({
url: 'http://localhost:8088/api/v1/ui/performance/custom_links?group='+id+'&user='+user,
dataType: 'json',
async: false,
success: function(data){
rdata = data.data;
}
});
return rdata;
}
表1
{
"response_code": 200,
"error_code": "",
"error_message": "",
"status": "SUCCESS",
"row_count": 5,
"data": [
{
"ID": "84",
"groupLabel": "Interface Util",
"isPrivate": "0",
"userId": "user1"
},
{
"ID": "85",
"groupLabel": "Hendrick Test Mweb",
"isPrivate": "0",
"userId": "user2"
},
{
"ID": "86",
"groupLabel": "test",
"isPrivate": "0",
"userId": "user4"
},
{
"ID": "87",
"groupLabel": "Interface Util",
"isPrivate": null,
"userId": "user3"
},
{
"ID": "88",
"groupLabel": "testing",
"isPrivate": "0",
"userId": "user5"
}
],
"meta": ""
}
表2
{
"response_code": 200,
"error_code": "",
"error_message": "",
"status": "SUCCESS",
"row_count": 2,
"data": [
{
"ID": "53",
"attributeId": "2194242",
"groupId": "85",
"isSummary": null,
"label": "DEV-SUPPORT-PC, DEV-SUPPORT-PC : Uptime",
"rrdGraphGroup": null
},
{
"ID": "54",
"attributeId": "2255447||2255453",
"groupId": "85",
"isSummary": null,
"label": "DEV-SUPPORT-PC, Intel(R)%2082578DC%20Gigabit%20Network%20Connection%20 : Utilization",
"rrdGraphGroup": "Utilization"
}
],
"meta": ""
}
表3
{
"response_code": 200,
"error_code": "",
"error_message": "",
"status": "SUCCESS",
"row_count": 5,
"data": [
{
"ID": "84",
"groupLabel": "Interface Util",
"isPrivate": "0",
"userId": "user1",
"children": ""
},
{
"ID": "85",
"groupLabel": "Hendrick Test Mweb",
"isPrivate": "0",
"userId": "user2",
"chlidren": [
{
"ID": "53",
"attributeId": "2194242",
"groupId": "85",
"isSummary": null,
"label": "DEV-SUPPORT-PC, DEV-SUPPORT-PC : Uptime",
"rrdGraphGroup": null
},
{
"ID": "54",
"attributeId": "2255447||2255453",
"groupId": "85",
"isSummary": null,
"label": "DEV-SUPPORT-PC, Intel(R)%2082578DC%20Gigabit%20Network%20Connection%20 : Utilization",
"rrdGraphGroup": "Utilization"
}
]
},
{
"ID": "86",
"groupLabel": "test",
"isPrivate": "0",
"userId": "user4",
"children": ""
},
{
"ID": "87",
"groupLabel": "Interface Util",
"isPrivate": null,
"userId": "user3",
"children": ""
},
{
"ID": "88",
"groupLabel": "testing",
"isPrivate": "0",
"userId": "user5",
"children": ""
}
],
"meta": ""
}
你需要使用回調並執行了AJAX調用已經結束,否則你是從_getJsonObject返回Ajax調用結束前。使用回調函數作爲該函數的第三個參數,並在使用data.data對該回調函數進行ajax請求調用的成功回調函數中使用。 – satchcoder 2015-02-09 10:21:24
即使使用'async:false',return語句也會在AJAX回調之前執行。 – 2015-02-09 10:21:41