开发者

Javascript XMLHttpRequests in Loop?

I am trying to save an array of records into a mysql database but I always get the abort message in firebug except for the last save. How do I save the records using a loop for XMLHttpRequest? Here is my code:

function savingCo开发者_如何学运维ntent()
{
   if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();

   }
   else
   {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }

   var rowindex = 0;

   for (x in globalObj.AddedRows)
   {
      var rowData = "?q=" + globalObj.AddedRows[rowindex];

      xmlhttp.open("POST", "insertRowData.php"+rowData, true);
      xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 
      xmlhttp.setRequestHeader("Content-Length",rowData.length); 
      xmlhttp.send(null);
      rowindex += 1;
}


There are quite a few problems with this code. Here are just the first ones I found:

  1. The for (x in object) syntax should only be used when you want to iterate over all fields in an object. In this case you want to iterate over an array, so you should do it like this:

    for (var rowindex = 0; rowindex < globalObj.AddedRows.length; rowindex++) {
    }
    
  2. When doing an HTTP POST, you shouldn't put the data you want to change into the URL. Put it in the body of the request - as the argument to xmlhttp.send(). You're actually explicitly passing a content length - that length is supposed to be the length of the data you pass to xmlhttp.send() - so by passing NULL this is almost certainly your main error.

  3. Rather than using Firebug, it'd be better to use xmlhttp.onreadystatechange to figure out which of your requests are succeeding or failing. Don't assume that once you have it debugged the first time, it will always succeed from then on. Handle errors.


In addition to dmazzoni:

Every time your for loop sends an async xml request it overrides the previous request and therefore the previous one is aborted. You should create a new XMLHttpRequest (or ActiveXObject for IE) inside your for-loop or wait for the HTTP return call, before sending a new request.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜