我從服務器響應中獲取完美創建的JSON對象。Javascript TypeError:JSON數組對象未定義
例如:
{
"users": [
{
"userId": 20410,
"firstName": "Viral",
"lastName": "Shah",
"loginId": "[email protected]",
"userRole": 3
},
{
"userId": 400881,
"firstName": "Viral",
"lastName": "Shah",
"loginId": "[email protected]",
"userRole": 0
},
{
"userId": 425622,
"firstName": "Viral",
"lastName": "Shah",
"loginId": "[email protected]",
"userRole": 0
}
]
}
我使用AJAX象下面這樣在JavaScript中使用此:
var jsonobj2 = null;
var respObj = getSearchedWPUsers(firstname, lastname, loginid); //return json response
var len = respObj.length;
jsonobj2 = eval('(' + respObj + ')');
var tablehtml = "<table><tr><td><b>First Name</td><td><b>Last Name</td><td><b>Login Id</td><td><b>Editing Rights</td></tr><tr></tr>";
for (i = 0; i < len; i++) {
tablehtml = tablehtml + "<tr>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].firstName;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].lastName;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td>";
tablehtml = tablehtml + jsonobj2.users[i].loginId;
tablehtml = tablehtml + "</td>";
//--------------
tablehtml = tablehtml + "<td><b>";
var role = jsonobj2.users[i].userRole;
if (role == 1 || role == 2 || role == 3) tablehtml = tablehtml + "<a href ='javascript:removeXML(" + jsonobj2.users[i].userId + ")'><u><font color='red'>Revoke access</font></a> ";
else tablehtml = tablehtml + "<a href ='javascript:generateXML(" + jsonobj2.users[i].userId + ")'><u><font color='blue'>Assign access</font></a> ";
tablehtml = tablehtml + "</td>";
tablehtml = tablehtml + "</tr>";
}
tablehtml = tablehtml + "</table>";
document.getElementById("TableHolder").innerHTML = tablehtml;
//--------------------------
它拋出錯誤像下面
TypeError: jsonobj2.users[i] is undefined
[Break On This Error]
tablehtml = tablehtml + jsonobj2.users[i].firstName;
與JSON.parse(serverresponse);
嘗試 - 沒什麼發生了
請幫助
你確定'respObj'是你認爲它是什麼嗎?從返回Ajax調用的函數返回值似乎很奇怪。請告訴我們它包含的內容。 –
你確定'respObj'包含了什麼嗎?您可能需要執行'async:false' ajax以便從ajax調用中返回某些內容。因爲ajax是異步的。 –
你是否檢查過螢火蟲中的respObj?檢查螢火蟲響應。 – Learner