我的网页上有以下表单和javascript功能。这是一个虚拟函数,我正在使用它来测试我想要做什么是可能的。如何使用提交按钮来激活AJAX功能?
我正在试图做的是有一个窗体发送一个AJAX请求到服务器,以便服务器可以更新数据库,而页面本身继续沿着它的预定路径。我处于紧张时刻,所以我很遗憾没有时间重写整个页面以更好地支持这一点。我的问题是xmlhttp
对象似乎没有正常返回。我得到一个readyState
的4,但status
为0.有人可以请解释我需要做什么?
这里是我的代码:
ajax.php
<html>
<head>
<script type="text/javascript">
function test(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
document.getElementById("new").innerHTML+="<b>"+xmlhttp.readyState+"</b> "+xmlhttp.status;
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("hello").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","response.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
if ($_POST){
echo $_POST['hello'];
}
?>
<form action="ajax.php" method="post">
<input type="text" name="hello" />
<input type="submit" value="submit" onclick="test();" />
</form>
<div id="hello"></div>
<h3>debug</h3>
<div id="new"></div>
</body>
</html>
response.php
<?php
echo "Hello there";
?>
编辑
请注意,我不想上一页默认行为。实际上,像往常一样提交forn 必须。我只是想为流程添加一个AJAX请求。
http://stackoverflow.com/questions/5081674/jquery-prevent-default-browser-form-submit-behaviour-but-submit-form-with-jquer – check123 2012-01-13 14:16:39
http://stackoverflow.com/questions/1357118/javascript-event-preventdefault-vs-return-false – check123 2012-01-13 14:17:39
@ check123请不要说我不想阻止默认行为。表单需要像平常一样提交,但我也希望AJAX请求也能发生。 – ewok 2012-01-13 14:18:44