我正在尝试验证数据库中是否存在输入的电子邮件,并根据此结果执行代码。为此,我调用了一个Javascript函数,该函数调用一个php页面的ajax jquery方法来检查id,输入的电子邮件是否在数据库中。使用的代码是:
function validateEmail()
{ var username= document.getElementByName("email").value;
alert("Username is"+ username);
$.ajax({
type: "POST",
url: "emailCheck1.php",
data: "username="+username,
success: function(result){
if(result=="checked"){
return true;
}
else
{
document.getElementById("errorEmail").style.display="inline";
return false;
} }
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});但问题是该函数在ajax方法完成之前返回值。所以返回值是不正确的。如何使函数在ajax方法完成之前不返回任何值,并根据ajax方法的返回值返回所需的值……任何帮助我们都将不胜感激。
发布于 2015-07-28 00:07:35
在ajax完成后,您需要使用回调来处理该值,或者使查询同步(这可能是错误的做法)。
如果您想在方法上设置一个参数,您可以查看函数的当前值来指定您的回调。
function partial(fn) {
// A reference to the Array#slice method.
var slice = Array.prototype.slice;
// Convert arguments object to an array, removing the first argument.
var args = slice.call(arguments, 1);
return function() {
// Invoke the originally-specified function, passing in all originally-
// specified arguments, followed by any just-specified arguments.
return fn.apply(this, args.concat(slice.call(arguments, 0)));
}
function doRequest()
{
callback = partial(doSomething, "Test Value");
$.post('action', {json_arg: "Test Arg"}, callback);
}https://stackoverflow.com/questions/31657912
复制相似问题