Javascript 如何访问 AJAX 的数组响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10261775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:33:04  来源:igfitidea点击:

How to Access Array response of AJAX

javascriptjquery

提问by Pawan

This is my AJAX call response which is in array format

这是我的 AJAX 调用响应,它是数组格式

[1,2,3,4,5,6]

[1,2,3,4,5,6]

success: function(outputfromserver) {


$.each(outputfromserver, function(index, el) 
{ 


});

How can we access outputfromserver all values ??

我们如何访问 outputfromserver 的所有值?

Means outputfromserver Zeroth value is 1 , 2nd element is 2 , -----so on

表示从服务器输出第零个值是 1 ,第二个元素是 2 ,-----等等

回答by Will Klein

It would help to know what your AJAX request looks like. I recommend using $.ajax() and specifying the dataType as JSON, or using $.getJSON().

了解您的 AJAX 请求是什么样的会很有帮助。我建议使用 $.ajax() 并将数据类型指定为 JSON,或者使用 $.getJSON()。

Here is an example that demonstrates $.ajax() and shows you how to access the returned values in an array.

这是一个演示 $.ajax() 的示例,并向您展示如何访问数组中的返回值。

$.ajax({
    url: 'test.json', // returns "[1,2,3,4,5,6]"
    dataType: 'json', // jQuery will parse the response as JSON
    success: function (outputfromserver) {
        // outputfromserver is an array in this case
        // just access it like one

        alert(outputfromserver[0]); // alert the 0th value

        // let's iterate through the returned values
        // for loops are good for that, $.each() is fine too
        // but unnecessary here
        for (var i = 0; i < outputfromserver.length; i++) {
            // outputfromserver[i] can be used to get each value
        }
    }
});

Now, if you insist on using $.each, the following will work for the success option.

现在,如果您坚持使用 $.each,以下内容将适用于成功选项。

success: function (outputfromserver) {

    $.each(outputfromserver, function(index, el) {
        // index is your 0-based array index
        // el is your value

        // for example
        alert("element at " + index + ": " + el); // will alert each value
    });
}

Feel free to ask any questions!

随意问任何问题!

回答by Juzer Ali

The array is a valid JSON string, you need to parse it using JSON parser.

该数组是一个有效的 JSON 字符串,您需要使用 JSON 解析器对其进行解析。

success: function(outputfromserver) {
    var data = JSON.parse(outputfromserver);
    $.each(data, function(index, el) { 
        // Do your stuff
    });
},
...

回答by Sampo Sarrala - codidact.org

You can use JS objects like arrays

你可以使用像数组这样的 JS 对象

For example this way:

例如这种方式:

// Loop through all values in outputfromserver
for (var index in outputfromserver) {
  // Show value in alert dialog:
  alert( outputfromserver[index] );
}

This way you can get values at first dimension of array, above for..loopwill get values like this:

这样你就可以得到数组第一维的for..loop值,上面会得到这样的值:

// Sample values in array, case: Indexed array
outputfromserver[0];
outputfromserver[1];
outputfromserver[2];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];

However, when implemented this way, by using for ( index in array )we not only grab indexed 1,2,3,4,...keys but also values associated with named index:

但是,当以这种方式实现时,通过使用for ( index in array )我们不仅可以获取索引1,2,3,4,...键,还可以获取与命名索引关联的值:

// Sample values in array, case: accosiated/mixed array
outputfromserver["name"];
outputfromserver["phone"];
outputfromserver[37];
outputfromserver[37];
outputfromserver["myindex"];
// So on until end of world... or end of array.. whichever comes first.
outputfromserver[...];

In short, array can contain indexed values and/or name associated values, that does not matter, every value in array is still processed.

简而言之,数组可以包含索引值和/或名称关联值,这无关紧要,数组中的每个值仍会被处理。

If you are using multidimensional stuff

如果你正在使用多维的东西

then you can add nested for (...)loops or make recursive function to loop through all and every value.

然后您可以添加嵌套for (...)循环或使递归函数循环遍历所有值。

Multidimensional will be something like this:

多维将是这样的:

// Sample values in array, case: indexed multidimensional array
outputfromserver[0][0];
outputfromserver[0][1];
outputfromserver[1][0];
outputfromserver[1][...];
outputfromserver[...][...];

Update, JSON object:

更新,JSON 对象:

If you server returns JSON encoded string you can convert it to javascript object this way:

如果您的服务器返回 JSON 编码的字符串,您可以通过以下方式将其转换为 javascript 对象:

try { 
    // Try to convert JSON string with jQuery:
    serveroutputobject = $.parseJSON(outputfromserver); 
} catch (e) {
    // Conversion failed, result is not JSON encoded string 
    serveroutputobject = null;
}

// Check if object converted successfully:
if ( serveroutputobject !== null ) {
    // Loop through all values in outputfromserver
    for (var index in serveroutputobject) {
        // Append value inside <div id="results">:
        $('#results').append( serveroutputobject[index] + "<br/>" );
    }
}
// In my own projects I also use this part if server can return normal text too:
// This way if server returned array we parse it and if server returns text we display it. 
else {
    $('#results').html( outputfromserver );
}

More information here

更多信息在这里

回答by ShivarajRH

$.ajax({
    type : "POST",
    dataType: "json",
    url : url,
    data:dataString,
    success: function(return_data,textStatus) {



         temperature.innerText=return_data.temp;
                   // OR
        **temperature.innerText=return_data['temp'];**  

    },
    error: function(jqXHR, textStatus, errorThrown) { 
                 alert("Error while accessing api [ "+url+"<br>"+textStatus+","+errorThrown+" ]"); return false;    
    }
 });