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.
精彩评论