Cli*_*ote 1 javascript ajax asynchronous
这就是我想要做的.
当我的表单上单击"提交"表单时,javascript函数将遍历表单的所有字段.
对于每个字段,将调用一个函数,该函数将返回true/ false指示它是否正确填充.
如果false返回a,则会在该字段旁边显示错误消息.
如果所有字段都正确,则提交表单.如果没有,则不提交.
这是棘手的部分.虽然大部分验证都是通过javascript完成的,但是需要通过ajax验证用户名和电子邮件,以查看用户名/电子邮件是否已被使用.
我目前用于此ajax函数的结构与此类似:
function validateSomething()
{
var valid;
$.post("something.php", {x:y},
function(data)
{
if (isSomething(data))
valid=true;
//Here referring to the valid variable
//set outside this function, in the
// parent function
else
valid=false;
});
return valid/
}
Run Code Online (Sandbox Code Playgroud)
但那目前不起作用.
我该怎么做才能使它工作,即我可以阻止validateSomething()函数返回一个值,直到内部函数设置为true/false?
会这样的工作:
function validateSomething()
{
var valid="unset";
$.post("something.php", {x:y},
function(data)
{
if (isSomething(data))
valid=true;
//Here referring to the valid variable
//set outside this function, in the
// parent function
else
valid=false;
});
//Loop without returning until valid is set to true or false
while (valid=='unset')
{
//Do nothing?
}
return valid/
}
Run Code Online (Sandbox Code Playgroud)
您可以强制ajax-call等待async:false.
像这样使用jquery:
function validateSomething() {
var valid;
$.ajax({
url: "something.php",
data: {x: y},
type: "GET",
async: false, // this makes the ajax-call blocking
dataType: 'json',
success: function (response) {
valid= response.valid;
}
});
return valid;
}
Run Code Online (Sandbox Code Playgroud)
然而,使用AJAX时的最大胜利是它是异步的.此同步调用可能会在浏览器等待服务器时锁定它.
| 归档时间: |
|
| 查看次数: |
7159 次 |
| 最近记录: |