javascript JQuery、AJAX:如何使用 json 返回值填充数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4566042/
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-10-25 14:06:55  来源:igfitidea点击:

JQuery, AJAX: How can I populate an array with a json return?

javascriptjqueryajaxarrays

提问by daveomcd

I'm trying to following code but only get "undefined" in the alert box. Anyone know how I can actually populate the array outside of the .ajax?

我正在尝试遵循代码,但在警报框中只显示“未定义”。任何人都知道我如何实际填充 .ajax 之外的数组?

$(document).ready(function() {

    var reviewArray = new Array();

    getReviews();

    alert(reviewArray[0]);

});

function getReviews()
{

   $.ajax({
    type : 'GET',
    url  : 'reviewbox.php',
    dataType : 'json',
    success  : function ( data ) {

    $.each( data.reviews, function( i, itemData ) {
       reviewArray[i] = itemData.review;
    });
    },
    error    : function ( XMLHttpRequest, textStatus, errorThrown) {
        var err = "An error has occured: " + errorThrown;
        $("body").append(err);
        }
    });

}

回答by Felix Kling

You have two problems:

你有两个问题:

  1. Ajax calls are asynchronous. When alertis executed, the array is not filled yet (the Ajax call did not return yet).
  2. The array reviewArrayis not in any (parent) scope of getReviews(i.e. not accessible from that function).
  1. Ajax 调用是异步的。当alert被执行时,阵列中不填充尚未(Ajax调用还不回)。
  2. 该数组reviewArray不在任何(父)范围内getReviews(即不能从该函数访问)。

Put the alertin the callback:

将 放入alert回调中:

$(document).ready(function() {  
    getReviews(function(reviewArray) {
         alert(reviewArray[0]);
    }); 
});

function getReviews(callback) {
    $.ajax({
        /*...*/
        success  : function (data) {
            var reviewArray = [];
            $.each( data.reviews, function( i, itemData ) {
               reviewArray[i] = itemData.review;
            });
            callback(reviewArray);
        },
        /*...*/
   });
}

If you want to do it with declaring reviewArraybeforehand, you also have to define getReviewsin the readycallback:

如果要reviewArray事先声明,还必须getReviewsready回调中定义:

$(document).ready(function() {  
    var reviewArray = [];

    getReviews(function() {
         alert(reviewArray[0]);
    });

    function getReviews(callback) {
        $.ajax({
            /*...*/
            success  : function (data) {
                $.each( data.reviews, function( i, itemData ) {
                   reviewArray[i] = itemData.review;
                });
                callback();
            },
            /*...*/
       });
    }
}); 

But this way, the actual flow of your application might be more confusing.

但是这样一来,您的应用程序的实际流程可能会更加混乱。

回答by NickAldwin

Try this:

试试这个:

$(document).ready(function() {

    getReviews();

});

function getReviews()
{

    var reviewArray = new Array();

   $.ajax({
    type : 'GET',
    url  : 'reviewbox.php',
    dataType : 'json',
    success  : function ( data ) {

    $.each( data.reviews, function( i, itemData ) {
       reviewArray[i] = itemData.review;
    });
    alert(reviewArray[0]);
    },
    error    : function ( XMLHttpRequest, textStatus, errorThrown) {
        var err = "An error has occured: " + errorThrown;
        $("body").append(err);
        }
    });

}