jQuery 迭代 $.get() 安全吗?
我在绑定下拉菜单时遇到问题。我认为问题出在我的 $.get()
中的回调。在循环中执行 gets 不安全吗?例如
//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 concrete answer.
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 concrete answer.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是您在 XHR 返回之前更改了 stateOneOrTwo,因此两个回调都将以等于
"stateTwo"
的stateOneOrTwo
运行。如果您只是调用 get 两次,则实际上不需要循环。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
是否会失败,但是,一种更安全(且正确)的方法是使用递归函数来确保请求在发送下一个之前完成。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.