Ajax JSON数组——访问信息

Ajax JSON Array - accessing the information

本文关键字:访问 信息 数组 JSON Ajax      更新时间:2023-09-26

我有以下代码:

$.getJSON('../_javascripts/array.php')
    .success(function(response) { console.info(response); alert("success"); })
    .fail(function(jqXHR, status, error){ console.info(error); alert("error"); });

在控制台中显示输出,但是,我试图访问该信息(在控制台中显示-它是一个数组),并且似乎无法访问。

控制台输出

Object {P5yTZ947: Array[3], 11y6tdo8: Array[3], 66j8ttk2: Array[3], 27c7uqv0: Array[3], 44f6hvt7: Array[3]…}

我已经试过了:

alert(response);
alert(response[0]);
var array = response;

所有这些都带回了undefined

显然我做错了什么,但我不太明白是什么。欢迎提出任何建议、反馈和意见

很难回答你,因为我们没有任何访问你的array.php文件的权限。尝试用以下代码调试response输出(您需要打开Developer Console):

$.getJSON('../_javascripts/array.php', function( data ) {
    $.each( data, function( key, value ) {
        console.log( key );
        for( var i in value ) {
            console.log( "  " + JSON.stringify(value[i]) );
        }
    });
});

尝试使用断点在Google Chrome控制台检查data (Ajax响应)变量内容。

从控制台输出来看,array.php返回的是一个包含数组的对象。

您对响应的处理必须来自$.getJSON();的回调函数

也就是说,在成功的情况下,响应对象的范围仅在成功函数内。把你的成功处理代码放在那里(或者从那里调用它),你就可以开始了。

例如:

function doSomethingWithSuccessResponse( response ){
  console.log( response );
  // Execute the rest of your success case logic here
}
$.getJSON('../_javascripts/array.php')
    .success(function(response) { doSomethingWithSuccessResponse(response); })
    .fail(function(jqXHR, status, error){ console.info(error); alert("error"); });

或者更简洁地说:

function doSomethingWithSuccessResponse( response ){
  console.log( response );
  // Execute the rest of your success case logic here
}
$.getJSON('../_javascripts/array.php')
    .success(doSomethingWithSuccessResponse)
    .fail(function(jqXHR, status, error){ console.info(error); alert("error"); });

对于失败的情况类似-在失败回调中执行失败处理逻辑。

看起来你的API返回了一个嵌入数组的对象:

Object {
  P5yTZ947: Array[3], 
  11y6tdo8: Array[3], 
  66j8ttk2: Array[3], 
  27c7uqv0: Array[3], 
  44f6hvt7: Array[3]…
}

使用对象循环语义遍历对象。然后使用内循环遍历数组的元素:

for (var key in response) {
   if (response.hasOwnProperty(key)) {
      // key is now "P5yTZ947" or "11y6tdo8", etc
      var innerArray = response[key];
      // Loop over the values of the inner array
      for( var i = 0; i < innerArray.length; i++ ){
        console.log( innerArray[i] );  // 
      }
   }
}