修改
我可以将JSON生成为:
"headers":[ "ID", "Organization Name", "Submission Date", "Status" ]
代替
"headers":{"Status":"","Submission Date":"","Organization Name":"","ID":""}
使用JsonArray / JsonObject?
原始问题:
我正在尝试在控制器中创建一个JSONArray并在jquery / ajax中使用它。但是当我尝试在javascript中访问json时,它不起作用。这是JSON输出(几乎我想要的除了标题只需要键):
[{"menu":{"extra":"","role":"users","name":"Home","url":"google.com"}},{"organization":{"status":"locked","submitted":"03/11/2015","name":"ABC Company","id":"1"},"headers":{"Status":"","Submission Date":"","Organization Name":"","ID":""}},{"notificationList":{"createdId":"21","startTimestamp":"2015-05-12T18:30:28.237Z","active":"true","endTimestamp":"2015-05-13T12:30:30.237Z","id":1,"description":"One","createdTimestamp":"2015-05-12T18:15:28.237Z"}},{"data":{"createdId":"251","startTimestamp":"2015-05-26T19:30:28.237Z","active":"true","endTimestamp":"2015-06-13T11:30:30.237Z","id":"102","description":"Notification 2","createdTimestamp":"2015-05-14T16:15:28.237Z"},"notificationHeaders":{"End Time":"","End Date":"","Active":"","Start Time":"","ID":"","Start Date":"","Description":""}}]
Javascript - 这是我失踪的地方:
mainmenu = (function () {
var mainmenu = null;
$.ajax({
type: "GET",
contentType: "application/json",
url: "<%=aURL%>",
dataType: "json",
success: function (mainMenuJson) {
alert(mainMenuJson.menu.url);
mainmenu = mainMenuJson;
}
});
return mainmenu;
})();
这里错误 - 未定义。
alert(mainMenuJson.menu.url);
alert(mainMenuJson)打印:
[object Object],[object Object],[object Object],[object Object]
当我尝试使用:
解析JSON时var content= JSON.parse(mainMenuJson);
我在第1行第2列出现了解析错误
一旦这个工作,我还需要使用javascript通过使用mainmenu变量来渲染整个页面。像这样:
var nheaders = mainmenu.notificationHeaders;
for(var i=0; i<nheaders.length; i++ ){
var notificationTableTheadTh = document.createElement("th");
notificationTableTheadTh.innerHTML = nheaders[i];
notificationTableTheadTh.setAttribute('scope',"column");
notificationTableTheadTr.appendChild(notificationTableTheadTh);
}
....
....
....
答案 0 :(得分:1)
它是一个JSON数组,所以你需要:
mainMenuJson[0].menu.url // <--- google.com
修改强>
您的代码可以重写为以下内容。
function getMenu() {
return $.ajax({
type: "GET",
contentType: "application/json",
url: "<%=aURL%>",
dataType: "json"
})
}
getMenu().done(function(json) {
var nheaders;
//Looping as you may not know the position of the key in your JSON. If you did, then it'd be simply --> var nheaders = json[3]["notificationHeaders"];
json.forEach(function(val, key) {
if (val.hasOwnProperty("notificationHeaders")) {
nheaders = val.notificationHeaders;
for (var nKey in nheaders) {
//Do stuff
alert ("Key: " + nKey + " and Value: " + nheaders[nKey]);
//Use jQuery for the below code chunk as well.
//var notificationTableTheadTh = document.createElement("th");
//notificationTableTheadTh.innerHTML = nheaders[i];
//notificationTableTheadTh.setAttribute('scope',"column");
//notificationTableTheadTr.appendChild(notificationTableTheadTh);
}
}
});
});
希望有所帮助。