2回复来自ajax调用php

时间:2015-05-29 08:32:16

标签: javascript jquery ajax

在下面的代码中,我需要来自响应的2个值

  1. 被调用页面网址的Html响应

  2. 用于获取页面 OR 在调用中使用的数组索引的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) {
    
        }
    });}
    

1 个答案:

答案 0 :(得分: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);

}