onreadystatechange function is not working in AJAX

后端 未结 4 619
没有蜡笔的小新
没有蜡笔的小新 2021-01-14 09:56

as far as XMLHttpRequest() Object is concerned, it is fine, the problem is with onreadystatechange for example if I put my code this way, it works perfect.<

4条回答
  •  感情败类
    2021-01-14 10:34

    Two things:

    xmlHttp.open("GET", "hello.txt", true);
    xmlHttp.onreadystatechange = handleServerResponse;
    xmlHttp.send();
    

    As you see, I removed the parentheses and I inverted the order of open and onreadystatechange.

    The first thing, is because otherwise you do not associate the function reference itself, but the function's return value – because, basically, you're executing it. It's the same difference to have:

    var a = sum(1, 2); // 3, assign to `a` the return value of `sum`
    var b = sum; // assign to `b` the `sum` function ref.
    var c = b(1, 2); // 3, therefore `b` is an 'alias' to `sum` 
    

    The second thing, it depends by the browser: for instance, some version of IE "reset" the onreadystatechange of a XMLHttpRequest instance, every time the open method is called. So if you set the onreadystatechange before the open, that works as "initializator", there is a chance, depends by the browser, that would be removed – and therefore never called – once the open method is called. So to be fully compatible, it's better set the onreadystatechange after the open method – but of course before the send.

提交回复
热议问题