胖鸭 2012-04-23 15:23 采纳率: 66.7%
浏览 21

了解Ajax调用流程

I am a bit confused in the call flow of Ajax, Could some one help me please?

My HTML:

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button>

My JavaScript:

var xmlhttp;

function loadXMLDoc(url, cfunc) {
    alert("4");
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    alert("5");
    xmlhttp.onreadystatechange = cfunc;
    alert("6");
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

function myFunction() {
    alert("1");
    loadXMLDoc("ajax_info.txt", function() {
        alert("2");
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert("3");
            document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
        }
    });
}​

According to me the Alert box sequence should be

1 2 3 4 5 6

But it is

1456222223

Could some one please explain me why is the function being called 1'st. I was in the impression untill the parameter values are ready the function cannot be called.

  • 写回答

2条回答 默认 最新

  • weixin_33749131 2012-04-23 15:25
    关注

    loadXMLDoc(...) is a normal function call.
    It executes immediately.

    The callback that you pass it (containing alert("2")) is only executed when something calls it; namely, when the XMLHTTPRequest raises onreadystatechanged.

    onreadystatechanged fires multiple times for different state changes, as you can see in the readyState property.

    评论

报告相同问题?