jQuery 迭代 $.get() 安全吗?

发布于 2024-12-02 04:56:09 字数 599 浏览 0 评论 0原文

我在绑定下拉菜单时遇到问题。我认为问题出在我的 $.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

﹏雨一样淡蓝的深情 2024-12-09 04:56:09

问题是您在 XHR 返回之前更改了 stateOneOrTwo,因此两个回调都将以等于 "stateTwo"stateOneOrTwo 运行。如果您只是调用 get 两次,则实际上不需要循环。

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

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

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');
嘿嘿嘿 2024-12-09 04:56:09

我完全不确定如果您在完成之前调用一个新的 $.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文