2015-05-29 29 views
0

在下面的代码,我需要从响应2个值2反应到PHP

  1. 被叫页面URL的

    HTML响应

  2. 这是用来获取URL的值页面在调用中使用的数组索引。

    for (i = 0; i < pageURLs.length; i++) { 
        $.ajax({ 
    
        url: pageURLs[i], 
        dataType: 'html', 
        statusCode: { 
         200: function(response) { 
          /*i am only getting access to the html of the page HERE*/ 
    
    
    
         }, 
         404: function() { 
           /*404 here*/ 
    
         } 
        }, 
        error: function(error) { 
    
        } 
    });} 
    

回答

3

编辑这里是这样,使用let更轻量级的方式。请参阅原始回复的解释。

注意这句法可能不与旧的浏览器兼容... :(

for (i = 0; i < pageURLs.length; i++) { 
    let j = i; 
    $.ajax({ 
     url: pageURLs[j], 
     dataType: 'html', 
     statusCode: { 
      200: function(response) { 
       /* now you can also access j */ 
       console.log("j=", j); 
      }, 
      404: function() { 
       /*404 here*/ 
      } 
     }, 
     error: function(error) { 
      // error processing 
     } 
    }); 
} 

原来的答复

你需要用你的循环体的功能,因为函数范围将保留在回调函数中,因此,您将能够在回调函数中检索正确的i值。

for (i = 0; i < pageURLs.length; i++) { 
    (function(i) { 
     $.ajax({ 
     url: pageURLs[i], 
     dataType: 'html', 
     statusCode: { 
      200: function(response) { 
      /*i am only getting access to the html of the page HERE*/ 
      /* now you can also access i */ 
      }, 
      404: function() { 
       /*404 here*/ 

      } 
     }, 
     error: function(error) { 

     }}); 
    }(i); 

}