开发者

Ajax send function wont' fire?

Whenever I run this file the code runs up to the point where the send function fires and then it only fires if I have an alert function directly behind it, if I take out the alert("sent"); out then it replies with ServerReadyyState is:1.

What could possibly be the problem? Someone please help, I've tried it on my local machine and on my personal server and got the same results. Any help is greatly appreciated.

The Code:

/**
 * @author d
 */
var xhr;

function getPlants(xhr) {
  try {
    xhr = new XMLHttpRequest();
  } catch (microsoft) {
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        xhr = false;
        alert("ajax not supported");
      }
    }
  }
  xhr.open("GET", "db_interactions.php", true);


  xhr.send(null);
  alert("sent"); //the send function only works if this alert functions is here
  if (xhr.readyState == 4) {

    return xhr.responseText;
  } else {
    alert("Server ReadyState is:" + xhr.readyState);
    xhr.开发者_如何学编程abort();
    //getPlants(xhr);       
  }
}


AJAX is asynchronus. You can't just check the ready state immediately after.

The correct design pattern is to assign a function for the AJAX call to run when the ready state changes.

xhr.onreadystatechange = function () { alert('It changed!') }

In that function, you'll want to check if the state is 4. If so, you're ready to process the output. If not, do nothing, since that function will be called a few times before the ready state is 4.


Requests take some amount of time. When adding an alert() the code is being stopped until the user clicks ok. So when you remove it the request is send and immedialty checked. Resulting in an unfinished request.

When you change your code to this:

xhr.onreadystatechange=state_change
xhr.send(null);

function state_change() {
    if(xhr.readyState==4) {
         return xhr.responseText;
    } else {
         alert("Server ReadyState is:"+xhr.readyState);     
    }
}

a certain function like in this case state_change gets called every time the state changes. So you can wait until the request is finished or until an errorcode comes up.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜