![](/img/trans.png)
[英]Using Javascript in HTML returning false even if the condition is true
[英]Function is returning false even the condition is true why?
function checkform(for1)
{
var result=checkform1(for1);
alert(result);
}
function checkform1(form)
{
var valid=false;
var val1 = document.getElementById('security_code').value;
$.get(url, function(data) {
if(data.toString()==val1.toString())
{
var elem = document.getElementById("captchaerr");
elem.style.visibility = 'hidden';
valid=true;
}
else
{
var elem = document.getElementById("captchaerr");
elem.style.visibility = 'visible';
valid=false;
}
});
return valid;
}
结果警报始终为false,即使条件(data.toString()== val1.toString())为true,控件如何通过它传递。 thnks ..
默认情况下,$。get aka Ajax.get是异步的(它在后台运行)。 因此,您的函数“ checkform1”将在Ajax请求完成并设置“ valid”变量之前返回。
不要使用toString()作为字符串。 toString()将返回string
。 只是测试data == val1
。
您正在进行异步调用,因此如果要检查结果,则必须在回调中执行此操作
function checkform1(form)
{
var valid=false;
var val1 = document.getElementById('security_code').value;
$.get(url, function(data) {
if(data.toString()==val1.toString())
{
var elem = document.getElementById("captchaerr");
elem.style.visibility = 'hidden';
valid=true;
}
else
{
var elem = document.getElementById("captchaerr");
elem.style.visibility = 'visible';
valid=false;
}
//here you will get the valid and
//not outside...outside it will be always false.
});
//This line will be executed immediately after the previous line
// and will not wait for the call to complete, so this needs to be done
// in the callback.
return valid;
}
如果您的“ get” ajax调用是异步调用,则可以使用回调来获取结果:
function checkform(for1)
{
checkform1(for1, function(result) //provide the callback to the async function
{
alert(result);
});
}
function checkform1(form, callback)
{
var valid=false;
var val1 = document.getElementById('security_code').value;
$.get(url, function(data)
{
if(data.toString()==val1.toString())
{
var elem = document.getElementById("captchaerr");
elem.style.visibility = 'hidden';
valid=true;
}
else
{
var elem = document.getElementById("captchaerr");
elem.style.visibility = 'visible';
valid=false;
}
if(callback)
callback(valid);// call the callback INSIDE of the complete callback of the 'get' jquery function
});
}
在条件之前,将Alert放在两个值alert(val1 +'---'+ data)上,看看其是否完全相同。
在比较之前也要修剪它们,以防万一有一些填充。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.