我最近一直在尝试以我拥有的表单使用 AJAX,以防止页面重新加载。我通过 thenewboston 的视频学习了 AJAX,并尝试将它与我的表单相匹配。
HTML:
<label for="f_name">Name:</label>
<input type="text" name="f_name" id="f_name" />
<label for="f_email">E-Mail:</label>
<input type="text" name="f_email" id="f_email" />
<label for="f_subj">Subject:</label>
<input type="text" name="f_subj" id="f_subj" /><br />
<div id="status"></div>
<button id="b_send" onClick="process()">Send</button>
JavaScript
function process() {
var name = encodeURIComponent(document.getElementById("f_name").value);
var email = encodeURIComponent(document.getElementById("f_email").value);
var sbj = encodeURIComponent(document.getElementById("f_subj").value);
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
xmlHttp.open("POST", "send.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send("name="+name+"&email="+email+"&subj="+sbj);
} else {
setTimeout('process()', 1000);
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4) { // AJAX is ready!
if (xmlHttp.status == 200) { // 200 = Comms went OK!
var xmlResponse = xmlHttp.responseXML;
var xmlDocumentElement = xmlResponse.documentElement;
var message = xmlDocumentElement.firstChild.data;
document.getElementById("status").innerHTML = '<span style="color:blue">' + message + '</span>';
} else {
alert('Something went wrong!');
}
}
PHP:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
$name = $_POST['name'];
$email = $_POST['email'];
$sbj = $_POST['subj'];
$src = 'BETA';
$to = "someone@somewhere.com";
$subject = "CONTACT | From: " . $name . " , " . $email . " | '" . $sbj . "' | " . $src . "";
$body = "
<html><body>
<h4>From: ".$name." , ".$email."</h4>
<h4>Subject: ".$sbj."</h4>
<h5>Source: BETA</h5>
</body></html>";
$headers = "From: someone@somewhere.com\r\n";
$headers .= "Reply-To: \r\n";
$headers .= "CC: \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$response = 'Error!';
if (mail($to, $subject, $body, $headers)) {
$response = 'Sent!';
} else {
$response = 'Error 202!';
}
echo '<response>';
echo strip_tags($response);
echo '</response>';
exit(); // I had to use exit() due to my hosting adding up code after every PHP page.
?>
单击按钮后,它会显示 PHP 页面,其中包含以下内容:
此 XML 文件似乎没有任何与之关联的样式信息。文档树如下所示。
以及它下面的 XML 代码:
<response>Sent!</response>
所以现在怎么办?