开发者

jQuery is it safe to iterate $.get()?

开发者 https://www.devze.com 2023-04-01 05:36 出处:网络
I\'m having a problem binding dropdowns.I think the problem is the callback in my $.get().Is it unsafe to perform gets in a loop?E.G.

I'm having a problem binding dropdowns. I think the problem is the callback in my $.get(). Is it unsafe to perform gets in a loop? E.G.

//on document ready
var stateOneOrTwo = "stateOne";
for(var i = 0; i < 2; i++){
   if(i === 1)
       stateOneOrTwo = "stateTwo";

   $.get(url,{},function(data) {
    var dropdown = stateOneOrTwo;
    $(dropdown).append(/*options*/);
   , 'json')};
}


This does appear to be unsafe. I threw DRY principles out the window. When I copy paste the code and just change the variable names involved I do not have any issues. I'll leave the question open for a concre开发者_开发知识库te answer.


The problem is that you are changing stateOneOrTwo before the XHR comes back, so both callbacks will be running with stateOneOrTwo equal to "stateTwo". If you are just calling get twice, you don't really need a loop.

$.get(url,{},function(data) {
    var dropdown = "stateOne";
    $(dropdown).append(/*options*/);
}, 'json');

$.get(url,{},function(data) {
    var dropdown = "stateTwo";
    $(dropdown).append(/*options*/);
}, 'json');


I am entirely not sure whether $.get will fail if you call a new one before it is finished, however, a more safe (and correct) approach would be to use recursive functions to make sure the request is complete before sending the next one.

0

精彩评论

暂无评论...
验证码 换一张
取 消