在while循环中使用jQuery AJAX请求 [英] Using jQuery AJAX requests in a while loop

查看:100
本文介绍了在while循环中使用jQuery AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码将要求用户输入他们的名字,将其发送到处理脚本(保存到数据库,验证等)并返回响应:

The following code will ask the user to enter their name, send it off to a processing script (saves to database, validates, etc) and returns a response:

var invalid = true;
while (invalid) {
    var name = prompt("Enter your name");
    $.ajax({
        type: "POST",
        url: "save.php",
        data: {
            "name": name
        }
    }).done(function(e) {
        //in this example, save.php returns "invalid" if the input did not pass validation
        invalid = e === "invalid";
    });
}

你可以看到我想要的一般想法,但问题是这个:即使我使AJAX调用同步,它也不会阻止循环继续。在 done 函数中放置 console.log 表明循环运行大约200次,直到我的服务器给出响应。

You can see the general idea I'm going for, but the problem is this: Even if I make the AJAX call synchronous, it doesn't block the loop from continuing. Placing a console.log in the done function reveals that the loop runs about 200 more times until my server gives a response.

服务器对用户的输入进行了大量的计算 - 我只是在这里使用名称作为例子。这不能在客户端进行。我怎样才能实现这个简单的,初学者的设计模式,实质上是在提醒我C#中的多线程噩梦?

The server does a heavy amount of calculations on the user's input - I'm just using name as an example here. This cannot be done client-sided. How can I implement this simple, beginner's design pattern across what is essentially reminding me of my multithreading nightmares in C#?

推荐答案

function validate(e)
{
    if(e === "invalid")
        setTimeout(submitName, 0);
}

function submitName()
{
    var name = prompt("Enter your name");
    $.ajax({
        type: "POST",
        url: "save.php",
        data: {
            "name": name
        }
    }).done(validate);
}

这篇关于在while循环中使用jQuery AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆