问题:
有没有办法暂停 javascript 直到 ajax 完成执行其成功功能?
相关代码:
function validateinput (name, parent, access)
{
//we assume that the input does not exist
exists = false;
//validate with server, expected response is true or false
$.post("AJAXURL", {action: "category", name: name, parent: parent},
function (data, textStatus, xhr)
{
//if returned true, the entry does exist for that parent
if (data == "true")
{
alert("AJAX");
exists = true;
}
else
exists = false;
});
switch (true)
{
//If the name field is blank (still displaying hint)
case (name == 'Subcategory Name' || name == 'Category Name'):
alert("Please enter a name");
break;
//if the name already exists for that parent
/*****/ case (exists == true):
alert("SWITCH");
break;
//if the parent field is displaying hint, assume parent is blank
case (parent == 'Parent Category'):
parent = '';
break;
//if the usergroup field is blank, assume value of parent
case (access == 'UserGroup Allowed To View'):
//if parent is also blank, assume lowest level usergroup access
if (parent == '')
access = "UserGroupTicketWorkers";
else
$.post("AJAXURL", {action: "specificcat", name: parent},
function (data, textStatus, xhr)
{
access = data['access'];
}
);
break;
default:
return true;
}
return false;
}
问题详细说明:
- 用户单击页面中的链接以触发此功能。
- 无论用户输入是否有错误,函数都会返回 true 或 false
- 当这段代码执行时,我在收到
alert("SWITCH");
之前收到alert("AJAX");
(第二种情况的条件目前是正确的,我在调试中将其反转以弄清楚发生了什么) - 我有一个临时解决方案,将第二种情况直接移动到默认值之前,但我的猜测是更快的计算机执行开关比较的速度可能比服务器提供响应的速度更快,因此不是永久解决方案。(除非它不能那样工作),并且如果我放入一个计时器来等待预设的时间,如果服务器运行速度比正常慢,则可能会出现同样的问题
- 我知道我没有从 ajax 调用中获取新值,因为有时间与服务器通信,所以,我的第一个想法是找到一种方法来暂停函数,直到 ajax 成功函数完成。
- 我不能将开关放在 ajax 调用中,因为这个函数需要返回一个值。
解析度
我使用了异步设置,它就像一个魅力。只需将我的代码从更改$.post()
为$.ajax()
并将其设置为发布
$.ajax(
{
url: "plugins/actions/edittickets/libs/changetickets.php",
type: 'POST',
data:
{
action: "category",
name: name,
parent: parent
},
async: false,
success: function (data, textStatus, xhr)
{
//if returned true, the entry does exist for that parent
if (data == "true")
exists = true;
}
});