开发者

Ajax function partially fails when alert removed

开发者 https://www.devze.com 2022-12-31 03:28 出处:网络
I have a problem in the following code: //quesry the db for image information function queryDB (parameters) {

I have a problem in the following code:

//quesry the db for image information
function queryDB (parameters) {
     var parameters = "p="+parameters;
     alert ("hello");


if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        // use the info
  alert (xmlhttp.responseText);
    }
  } 

    xmlhttp.open("POST", "js/imagelist.php", true);
    //Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
}

which is call from this function:

function buildGallery() {

    var images = document.getElementsByTagName("img");
    for (var i = 0; i< images.length; i++) {
       开发者_StackOverflow if (images[i].getAttribute("id").split("_")[0] == "onshow") {

            var parameters = images[i].getAttribute("id").split("_")[1];

            queryDB (parameters);
        }
    }

}

When I remove the alert statement 4 lines down in the queryDB function I hit problems. This function is being called by a loop, and without the alert, I only get results for the last value sent to this function. With it, I get everything I was expecting and really I'm at a loss to know why.

I've heard that this may be a timing issue as I'm sending new requests before the old one is finished. I also heard polling being mentioned, but I can't find any information detailed enough.

I'm new to synchronous services and I'm not really aware of the issues.


Actually, the problem is that you're using a global variable. Add:

var xmlhttp;

to the beginning of queryDB

As TriLLi notes, the alert hides this problem by giving the prior call time to finish before overwriting it.

0

精彩评论

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