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

$.ajax({
    type:"GET",
    url:"question.xml",
    dataType: "xml",
    success: function(data) {

        $(data).find('item').each(function() {

            var question = $(this).find('question').text();
            var answer = $(this).find('qid').text();
            var opt1 = $(this).find('ans1').text();
            var opt2 = $(this).find('ans2').text();
            var opt3 = $(this).find('ans3').text();
            var opt4 = $(this).find('ans4').text();

            questions.push({'question':question, 'answer':answer, 'opt1':opt1, 'opt2':opt2, 'opt3':opt3, 'opt4':opt4});
        });
        alert(questions.length); // here it shows length as 20
    }
});
alert(questions.length); // here it shows length as 0 });

我有一个声明为全局的数组(问题),问题是当我访问 ajax 成功内的数组时,它有 20 个元素,但是当我尝试访问数组时,数组长度变为 0。

有人可以解释我做错了什么。

4

3 回答 3

1

$.ajax is async.

Your alert at the last line was executed before any questions are pushed in.

于 2013-08-17T06:44:44.920 回答
0

$.ajax queues a request to the web server and returns immediately.

Therefore, the bottom alert runs before the data is ready.

When the data is ready, the success function is run, and the data appears.

You should do any processing of the data in the success function, or by calling from the success function.

See How do I return the response from an asynchronous call? for confirmation and additional discussion.

于 2013-08-17T06:44:15.247 回答
0

Ajax is asynchronous. This means that you order the browser to execute the ajax request, and the script will immediatelly continue with the rest of the script. Once the ajax request is completed, it will call the success handler of your ajax call. It will first reach

alert(questions.length); // here it shows length as 0

And when the page in your ajax call is finally loaded it will execute

alert(questions.length); // here it shows length as 20

If you need to perform actions on the result from the ajax call, you need to do it all in the success handler.

于 2013-08-17T06:45:24.483 回答