这个Ajax javascript代码的控制流程是什么?

时间:2017-10-23 19:17:30

标签: javascript json ajax

以下是代码:

var clickCounter = 0;

function clickme()
{   
    console.log("1value of clickCounter="+clickCounter);
    var ourRequest = new XMLHttpRequest();//we are just defining the request over here
    console.log("1.1value of clickCounter="+clickCounter);
    ourRequest.open('GET', 'http://localhost/ajaxTutorials/js/data'+clickCounter+'.json');
    console.log("1.2value of clickCounter="+clickCounter);
    ourRequest.onload = function()
    {
        //console.log(ourRequest.responseText);//just output the data as text
        console.log("2value of clickCounter="+clickCounter);
        var ourData = JSON.parse(ourRequest.responseText);
        //console.log(ourData[0].name);
        renderHTML(ourData);
    }
    ourRequest.send();//now we are actually sending the request
    console.log("1.3value of clickCounter="+clickCounter);
    clickCounter++;
    console.log("1.4value of clickCounter="+clickCounter);
}

这是我的控制台日志:

main.js:6 1value of clickCounter=0
main.js:8 1.1value of clickCounter=0
main.js:10 1.2value of clickCounter=0
main.js:20 1.3value of clickCounter=0
main.js:22 1.4value of clickCounter=1
main.js:19 GET http://localhost/ajaxTutorials/js/data0.json 404 (Not Found)
clickme @ main.js:19
onclick @ (index):6
main.js:14 2value of clickCounter=1
VM76:1 Uncaught SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.ourRequest.onload (main.js:15)
ourRequest.onload @ main.js:15
XMLHttpRequest.send (async)
clickme @ main.js:19
onclick @ (index):6

据我所知,它的执行应该是这样的,所以它按照

的顺序打印控制台日志

1

1.1

1.2

2

1.3

1.4

因为在到达myRequest.send()时应该调用onload函数。

0 个答案:

没有答案