日期:2014-05-17  浏览次数:20461 次

使用onsubmit事件触发ajax时返回值怎么返回
这个是表单

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>


</head>

<body>

<form action="abc.php" method="post" name="form" onSubmit="return check_form()"/>
用户名<input type="text" name="username" id="username" />
验证码<input type="text" name="identifying_code" id="identifying_code"/>
<input type="submit" name="login" value="登录">
</form>
<div id="tishi"></div>
<script language="javascript" src="js/xmlhttprequest.js"></script>
<script language="javascript" src="js/js2.js"></script>
</body>
</html>


这个是xmlhttprequest.js页面

var xmlhttp = false;
if (window.XMLHttpRequest) {  //Mozilla、Safari等浏览器
xmlhttp=new XMLHttpRequest();

else if (window.ActiveXObject) {  //IE浏览器
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e) {}
}
}


这个是js2.js页面里面有我标记的路线可以看到整个执行的过程。

var flag;
function check_form(){

    var username=document.getElementById('username').value;
var identifying_code=document.getElementById('identifying_code').value;
url='login_chk.php?username='+username+'&identifying_code='+identifying_code;
alert('这里第1步');
xmlhttp.open('get',url,true);
alert('这里第2步');
xmlhttp.onreadystatechange = function(){
alert('这里第5步');
if(xmlhttp.readyState == 4){
alert('这里第6步');
if(xmlhttp.status == 200){
alert('这里第7步');
msg = xmlhttp.responseText;
alert('这里第8步');

if(msg==1){
document.getElementById("tishi").innerHTML="<font color='#FF0000'>输入正确正在跳转</font>";
flag=true;

}
else{
document.getElementById("tishi").innerHTML="<font color='#FF0000'>用户名或者密码错误</font>";
flag=false;
}
alert('这里第9步');

    }
    }

//alert(flag);
}
xmlhttp.send(null);
alert('这里第3步');


if(flag==true){
alert('这里是true');
alert(flag);
return true;
}
else {
alert('这里第4步');
alert(flag);
return false;
}

}

这个是login_chk.php页面

<?php
if(strcmp($_GET['username'],'abcd')==0&&strcmp($_GET['identifying_code'],'abcd')==0){
$msg=1;

}
else{
$msg=0;
}

echo $msg;

?>




最重要的是要取得check_form的返回值,才能决定表单是否能提交。求高手更改代码取到check_form的返回值
------解决方案--------------------
xmlhttp.open('get',url,true);