开发者

JS not working properly

Following JS is not working properly:

document.getElementById("btn").value="harry";
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url, false);
xmlhttp.send(null);
document.getElementById("btn").value="joy";

The default value of btn is joy. When I run this the value of btn is not changing. All other things are working fine.

I want to开发者_如何学Python see the value change to "harry" while ajax request is running.

Why value is not changing? How to solve it?

HTML code:

<input id="btn" type="button" value="joy" onclick="change(id)" />


The default value of id is joy. When I run this the value of id is not changing. All other things are working fine.

The end result of your code is to set the value property of the element id to "joy". You change it temporarily to "harry", but then almost immediately change it back to "joy".

If you're expecting to see the value change to "harry" while your synchronous ajax request is running, you're likely to be disappointed. Synchronous ajax requests completely lock up the UI of most browsers, preventing any changes you make from being displayed until the request completes — and of course, in your case, you're changing the value back to "joy" when that happens, so...

If you want to see "harry" while the request is running, make it asynchronous:

document.getElementById("id").value="harry";
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = handleReadyStateChange;
xmlhttp.send(null);
function handleReadyStateChange() {
    if (xmlhttp.readyState == 4) {
        // Complete
        document.getElementById("id").value="joy";
    }
}

Live examples:

  • Synchronous version (nothing shows during the request on most browsers)
  • Asynchronous version (things get shown, because request is async)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜