没有动态参数的jquery ajax回调函数

时间:2022-10-23 20:38:23

I have an array with objects, I want to save each one of them via GET, and update certain params in the callback, bot

我有一个包含对象的数组,我想通过GET保存它们中的每一个,并更新回调中的某些参数,bot

the html:

<html><body><div id='test'><div id="a">a</div><div id="b">b</div></div></body></html>

the js:

$.map($("#test > div"), save)

save = function(o,i){
 itt = $(o)
 tmp = {'desc':itt.html()};
 $.get('ajax/update_post', {'data':array2json(tmp)}, function(a){ 
   alert(itt.attr('id'))
   updatePostBack(a,itt)
   })
 }

updatePostBack = function(a,item){
 alert(item.attr('id'))
}

the updatePostBack is always receiving the las item! how can I pass the right id or object to a callback function in js / jquery?

updatePostBack总是收到las项目!如何将正确的id或对象传递给js / jquery中的回调函数?

1 个解决方案

#1


The solution is so sadly mundane: you needed to add var in front of your variables to declare them as new. They were being overwritten inappropriately by the next iteration before the first one could complete. This code works for me:

解决方案非常平凡:您需要在变量前面添加var以将它们声明为新变量。在第一次迭代完成之前,它们被下一次迭代不恰当地覆盖。这段代码适合我:

save = function(o,i){
    var itt = $(o)
    var tmp = {'desc':itt.html()};
    $.get('ajax/update_post', {'data':array2json(tmp)}, function(a){
        alert(itt.attr('id'))
        updatePostBack(a,itt)
    })
}

updatePostBack = function(a,item){
    alert(item.attr('id'))
}

$.map($("#test > div"), save);

I also moved the map statement to the end so that it's calling the save function after it's been declared.

我还将map语句移动到最后,以便在声明后调用save函数。

#1


The solution is so sadly mundane: you needed to add var in front of your variables to declare them as new. They were being overwritten inappropriately by the next iteration before the first one could complete. This code works for me:

解决方案非常平凡:您需要在变量前面添加var以将它们声明为新变量。在第一次迭代完成之前,它们被下一次迭代不恰当地覆盖。这段代码适合我:

save = function(o,i){
    var itt = $(o)
    var tmp = {'desc':itt.html()};
    $.get('ajax/update_post', {'data':array2json(tmp)}, function(a){
        alert(itt.attr('id'))
        updatePostBack(a,itt)
    })
}

updatePostBack = function(a,item){
    alert(item.attr('id'))
}

$.map($("#test > div"), save);

I also moved the map statement to the end so that it's calling the save function after it's been declared.

我还将map语句移动到最后,以便在声明后调用save函数。