这是我的 AJAX 调用响应,它是数组格式的
[1,2,3,4,5,6]
success: function(outputfromserver) {
$.each(outputfromserver, function(index, el)
{
});
我们如何访问 outputfromserver 的所有值??
表示 outputfromserver 第 0 个值为 1,第 2 个元素为 2,-----依此类推
最佳答案
了解您的 AJAX 请求是什么样的会有所帮助。我建议使用 $.ajax() 并将数据类型指定为 JSON,或者使用 $.getJSON()。
这是一个演示 $.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
}
}
});
现在,如果您坚持使用 $.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
});
}
如有任何问题,请随时提出!
关于javascript - 如何访问 AJAX 的数组响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10261775/