I'm wondering why in the code below the i variable still shows "5" instead of showing "1" then "2" then "3" and so on ? Must be a scope issue but I don't really get it as I changed the scope of i variable in global and dom scope and still getting the same problem. When I alert i outside the ajax function, it works well.

我想知道为什么在下面的代码中,I变量仍然显示"5"而不是显示"1"然后"2"然后"3"等等?必须是一个范围问题,但我并没有真正理解,因为我在全局和dom范围中改变了I变量的范围,仍然得到了相同的问题。当我在ajax函数外部警告I时,它运行良好。

for (var i = 0; i < 5; i++) {   
   $.ajax({
        url: '/echo/html/',
        method:'post',
        data: {
            html: 'Ajax data'
        },
        success: function (resp) {
            $('#success').append(i) // always 5
        }
    })
    $('#outsideAjax').append(i); // is okay
}

Here is the fiddle

这是小提琴

EDIT :

编辑:

I went for @Tushar Gupta solution as it best suits my needs but I get another issue, the iteration won't work if I set this option : processData: false

我选择了@Tushar Gupta解决方案,因为它最适合我的需求,但我又遇到了另一个问题,如果我设置了这个选项,那么迭代将不起作用:processData: false。

See the fiddle

看到小提琴

Why is this not working ?

为什么它不能工作?

4 个解决方案

#1


0

fiddle Demo

小提琴演示

var i = 0;

function ajax_call() {
    $.ajax({
        url: '/echo/html/',
        method: 'post',
        data: {
            html: 'Ajax data'
        },
        success: function (resp) {
            $('#success').append(i++);
            if (i < 5) {
                ajax_call();
            }
        }
    });
    $('#outsideAjax').append(i);
};
ajax_call();

更多相关文章

  1. 范围变量值的变化没有反映在我的字符串中
  2. 开心菜鸟系列----变量的解读(javascript入门篇)
  3. 如何使用变量创建数组?
  4. Angularjs:如何将范围变量传递给指令?
  5. 如何将razor变量传递给js
  6. 如何从Vue.js中的变量名加载组件?
  7. 将对象值传递给指令而不是任何其他数据变量
  8. 关于JavaScript变量声明及其初始化的问题
  9. 如何使用变量填充iframe源?

随机推荐

  1. php实现分页的原理及步骤
  2. 【哈希密码】PHP比md5更安全的加密方式
  3. PHP面向对象简易验证码类
  4. php反射机制用法详解
  5. 通过实例详细讲解PHP垃圾回收机制
  6. php对象转数组的函数
  7. 正则表达式详细基础实例解析
  8. 详细介绍php迭代器的作用
  9. php日期格式化方法详解
  10. PHP实现文件上传下载实例详细讲解