AJAX PHP未返回值



我不确定我缺少了什么。我下面的语法有什么问题吗?我试图使用HTML表单请求一个答案,然后用PHP脚本根据一个值检查答案。

<!DOCTYPE html>
<html>
<head>
<title>Verify Identity</title>
</head>
<script>
function verify(e) {
if((e && e.keyCode == 13) || e == 0) {
document.forms.verifyForm.submit();
var golfer = document.getElementById("mgolf").value;
// window.alert("You answered: " + golfer);
//adding the ajax php call attempt 1 
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("servRes").innterHTML = this.responseText;
}
};
xmlhttp.open("GET", "checkanswer.php?q=", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}            
}
</script>
<body>
<h2>Welcome Ben</h2>
<div onKeyPress="return verify(event)">
<form id="verifyForm" onsubmit="return false;">
Question 1 text:</br> <input type="text" id="mgolf">
</form>
</div>
<div id="test"> 
<p id="servRes">replace</p>
</div>
</body>
</html>

和PHP

<?php
//create correct answer for test question
$answer = "Ben";
$q = $_REQUEST["q"];
if($q == $answer) {
echo "correct answer";
} else {
echo "incorrect answer";
}
?>

它不起作用,因为您正在调用.submit((;在form元素上,结果会刷新页面,但您不会看到XMLHttpRequest的结果。删除这一行并修复"innterHTML"可以使代码正常工作。

<!DOCTYPE html>
<html>
<head>
<title>Verify Identity</title>
</head>
<script>
function verify(e) {
if((e && e.keyCode == 13) || e == 0) {
// document.forms.verifyForm.submit();
var golfer = document.getElementById("mgolf").value;
// window.alert("You answered: " + golfer);
//adding the ajax php call attempt 1 
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("servRes").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "checkanswer.php?q=", true);
// xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}            
}
</script>
<body>
<h2>Welcome Ben</h2>
<div onKeyPress="return verify(event)">
<form id="verifyForm" onsubmit="return false;">
Question 1 text:</br> <input type="text" id="mgolf">
</form>
</div>
<div id="test"> 
<p id="servRes">replace</p>
</div>
</body>
</html>

最新更新