在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);
}