我正在创建一个可以使用PHP通过电子邮件发送数据并使用JavaScript显示灯箱效果的表单。因为我无法刷新页面,所以我决定使用AJAX将数据发送到PHP,但是我无法获得执行AJAX调用的代码。我在互联网上创建了这个代码,我可以按原样使用它,但是当我将它实现到我的页面时,它只是没有用。
以下是代码:
var time_variable;
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var txtname = document.getElementById("email");
xmlhttp.open("POST","contactScript.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("email=" + txtname.value); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
每次运行代码时,我总是偶然发现警报。
也许值得一提的是,我从id = email的文本输入字段收集电子邮件数据,我无意更新任何字段,除了显示灯箱效果。
任何帮助将不胜感激。
这是PHP代码(contactScript.php):
$field_email = $_POST['email'];
$mail_to = 'myemail@mydomain.com';
$subject = 'Message from a site visitor '.$field_name;
$body_message .= 'E-mail: '.$field_email."\n";
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
?>
不确定这是否有帮助,但我怀疑我的提交按钮有问题: