【发布时间】:2017-07-26 13:34:06
【问题描述】:
我正在使用 Javascript 和 jQuery 验证表单。
在验证函数结束时,我只是 AJAX 来检查 SQL 数据库中的条目,看看它是否已经存在。我的工作正常,但我似乎无法更新 Javascript 变量以指示检查是否返回该条目是否存在。以下是验证功能的精简版。
如果客户存在,最后当我执行 AJAX 调用时,我尝试将 isformcomplete 变量设置为 false,但这不起作用,就好像它没有读取该行并且没有正确设置,表单被错误提交。
我在这里缺少什么? AJAX 调用工作正常。谢谢。
<form method="post" action="../../../scripts/create-customer.asp" id="create-customer" onsubmit="return create_customer();">
function create_customer()
{
var isformcomplete = true;
message = "The following tasks need to be completed before continuing:\n\n";
if ( $("#customerno").val() == "" )
{
message += "* Select the customer's country and enter its unique identifier\n";
isformcomplete = false;
}
if ( $("#product").val() == "" )
{
message += "* Select a product\n";
isformcomplete = false;
}
if (isformcomplete == false)
{ alert(message); }
else
{
$("#alertsDynamic").slideUp();
$.post("/global-marketing/scripts/check-new-customer.asp",{ fromsubmit: true, customer: $("#customerno").val()+"|"+$("#product").val()},
function(data, status)
{
if ( data == "true" )
{
$("#error-message").html($("#customerno").val()+" "+$("#product").val()+" already exists");
$("#alertsDynamic").slideDown();
isformcomplete = false;
}
}
);
}
return isformcomplete;
【问题讨论】:
-
可以尝试使用
if (data == true)或if (data)之一来代替if ( data == "true" ) -
ajax 调用是异步的。在收到ajax请求的回复之前,执行可能已经到了函数的末尾。
-
@jingesh 这不是问题,之后是代码块,只是没有设置 isformcomplete 变量
-
@astrocrack 啊,我明白了。似乎不是一种让它为此目的工作的方法。
-
是的,您应该始终小心异步请求 最佳答案似乎可以解决这个问题。
标签: jquery ajax validation