Jquery错误和正确的循环索引

标签 jquery ajax

假设我有这个:

for( i = 0; i < 10; i++ )
{
    $.ajax({
        type: "POST",
        url: "geocode-items.php",
        async: true,
        data: {  
            key: i
        },
        success: function( data )
        {
            // data returns the index I passed into the script with the data property.
        },
        error( a, b, c )
        {
            alert( i ); // this obviously won't work
        }
    });    
}

警报(我);在错误部分不会提醒正确的索引。虽然在成功时我可以传回放入 geocode-items.php 脚本的 key ,但我无法在错误部分传回任何内容。

您知道在触发错误方法时如何引用通过请求发送的原始数据吗?

类似于 this.data.key 的东西?这样我就可以报告我所停留的特定对象的错误?而不必编写一些通用的“有错误代码,但我不知道在哪里”

最佳答案

您应该阅读一些有关 javascript 范围和闭包的内容。 在您的情况下,每个错误回调的值 i 都是相同的,并且由于 ajax 是异步的,因此所有的 i 都是 10。

javascript 仅具有基于函数的作用域,没有基于 block 的作用域。 您可以做的是创建一个匿名函数,将值传递给 (function(param1) { } )(value) 该函数将立即被调用。然后将函数的参数绑定(bind)到该函数调用。

for( i = 0; i < 10; i++ )
{
    (function(idx) {
       $.ajax({
           type: "POST",
           url: "geocode-items.php",
           async: true,
           data: {  
               key: idx
           },
           success: function( data )
           {
               // data returns the index I passed into the script with the data property.
           },
           error: function( a, b, c )
           {
               alert( idx ); // this obviously won't work
           }
        });
    })(i);   
}

关于Jquery错误和正确的循环索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14399399/

相关文章:

javascript - 单击按钮时,如何在发送 ajax 之前调用验证函数?

javascript - Rails 根据用户输入动态更新 View

PHP MySQL 和 ajax 实践项目

jQuery,Tampermonkey 没有冲突

javascript - AJAX数据响应-如何解析html

javascript - 在嵌套的 json 对象中查找和更新

ajax - Ajax 调用次数与数据大小

javascript - 我怎样才能得到点击按钮的动态值 id 或 data 属性

javascript - WordPress:悬停不起作用时尝试显示子菜单

jquery向div添加不存在的内容?