开发者问题收集

Javascript TypeError:JSON 数组对象未定义

2013-01-11
5252

我从服务器响应中获取了一个完美创建的 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
        }
    ]
}

我在 JavaScript 中使用 AJAX 如下:

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); -- 什么也没发生

请帮忙

1个回答

尝试以下方法:

991966798

据我了解, respobj 是一个包含JSON响应的字符串,但仍然需要解析它。因此,如果您执行 respobj.length ,则可以正确获取字符串的长度,但不能正确地获取用户数组的长度。另外,我建议您使用 json.parse (浏览器可用时)来解析此响应,而不是使用 eval

161207270

但是,正如Felix Kling和Aamir Adnan所说,Ajax调用大多是异步的,因此您可以将回调函数作为参数传递,它将作为您的意愿处理响应:

088276815
Danilo Valente
2013-01-11