我正在尝试创建一个无需页面刷新即可提交的表单,但不能使用jQuery实现。我似乎找不到任何不涉及jQuery的解决方案,因此我想知道我目前的做法有什么问题,以及如何修复它。
HTML
HTML
<form id="contactForm" name="contactForm" method="post" onsubmit="return validate(this);">
<fieldset>
<ol>
<li><label for="email">Email Address</label><input class="text" id="email" name="email" size="30" type="text"></li>
<li><label for="firstName">First Name</label><input class="text" id="firstName" name="firstName" size="30" type="text"></li>
<li><label for="lastName">Last Name</label><input class="text" id="lastName" name="lastName" size="30" type="text"></li>
<li><label for="message">Message</label><textarea cols="40" id="message" name="message" rows="20"></textarea></li>
</ol>
<input class="button" id="contactSubmit" name="submit" type="submit" value="submit">
</fieldset>
</form>
Ajax/JS
function observeEvent(target, eventName, observerFunction, useCapture){
if (target.addEventListener) {
target.addEventListener(eventName, observerFunction, useCapture);
} else if (target.attachEvent) {
target.attachEvent("on" + eventName, observerFunction);
}
}
function start() {
var xmlhttp = new XMLHttpRequest();
var contentDiv = document.getElementById("success");
xmlhttp.open("POST", "processor.php", true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
contentDiv.innerHTML=xmlhttp.responseText;
alert('message sent!');
}
}
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
xmlhttp.send("email=" + email +"&firstName=" + firstName + "&lastName=" + lastName + "&message=" + message);
}
observeEvent(window,"load",function() {
var btn=document.getElementById("contactSubmit");
observeEvent(btn,"click",start);
});
PHP为佳
<?php
$fName = $_POST['firstName'];
$lName = $_POST['lastName'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'xxx@xxx.com';
$subject = 'the subject';
$message = 'FROM: ' . $fName . ' ' . $lName . ' Email: ' . $email . 'Message: '. $message;
$headers = 'From: ' . $to . "\r\n";
$mailRegex = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
if (preg_match($mailRegex, $email)) { // this line checks that we have a valid email address
mail($to, $subject, $message, $headers);
echo "Your email was sent!";
}