开发者

Javascript: XMLHttpRequest Task Switch

开发者 https://www.devze.com 2022-12-20 04:39 出处:网络
document.getElementById(\'contactButton\').value = \"Sending\"; xmlhttp.onreadystatechange=stateChanged;
document.getElementById('contactButton').value = "Sending";
xmlhttp.onreadystatechange=stateChanged;

xmlhttp.open("GET",url,false);开发者_运维技巧
xmlhttp.send(null);
function stateChanged(){
    if (xmlhttp.readyState==4) {
    var response = xmlhttp.responseText;
    if(response == "true"){
        document.getElementById('contactButton').value = "Sent :)";
    }
}

When running this javascript, contactButton never gets set to "Sending...". It hangs for one second, and then changes to "Sent :)".

I'm not real sure about the processing order of javascript, but it seems like it needs some sort of task switch to process the XMLHttpRequest().

This is obviously an abbreviated code, but I have several other javascript/css things I am trying to do before the xmlhttp. It seems like the xmlhttp just takes over when the request is sent.

Any ideas?


You're passing false to open, so it's running synchronously. That means it doesn't use the readyState and instead just delays until the request completes. If you want to do sync, it should be:

xmlhttp.open("GET",url,false); 
xmlhttp.send(null); 
if(xmlhttp.status == 200)
{
  var response = xmlhttp.responseText;
  document.getElementById('contactButton').value = "Sent :)";
}

You should change to async to avoid hanging your script, and you will probably find it easier to use a JavaScript library.

0

精彩评论

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