我似乎无法弄清楚如何使用 ajax 发布。我做了一个愚蠢的形式来尝试它,即使在将它一直削减到只有两个值之后,仍然无法得到任何工作。我的html是这样的:
<html>
<head>
<script type="text/javascript" src="j.js"></script>
<title>Test this<
<body>/title>
</head>
<form name="testForm" onsubmit="postStuff()" method="post">
First Name: <input type="text" name="fname" id="fname" /><br />
Last Name: <input type="text" name="lname" id="lname" /><br />
<input type="submit" value="Submit Form" />
</form>
<div id="status"></div>
</body>
</html>
然后,到目前为止,我的外部 javascript 只是一个函数:
function postStuff(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "processForm.php";
var fn = document.getElementById("fname").value;
var ln = document.getElementById("lname").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
虽然我的 php 只是回显这些东西:
<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
echo $firstname ." - ". $lastname ."<br />";
?>
我在萤火虫或 chrome 的工具中找不到任何问题。我做错了什么可以吗?