我在理解和实现AJAX的WP方式时遇到了很大的问题。我有一个“正常”的设置,只是在提交表单时,页面会用额外的页眉/页脚复制自己,这可能是必须的,我没有在wp的每个方面都这样做。叹气我真的很高兴它能正常运行,现在我必须用不同的方法重做它。
嗯,我知道我应该排队并本地化我的js,我已经在我的函数中完成了这项工作。php-这样可以吗?至少它已加载,但我以后无法完全使用它。我还知道本地化允许我使用管理ajax。应该使用php来完成此操作。是的,到目前为止还不错。我可以看到它已正确加载,并且具有指向管理ajax的正确路径。php检查我的页面时。
这就是我迷路的地方。我不知道该把什么代码放在哪里。我已经花了好几个小时试图重新排列代码,但我并没有走得更远。
这就是我目前拥有的-我应该怎么做?
解析器。php
<?php
if ( isset($_POST[\'name\']) && isset($_POST[\'mail\']) && isset($_POST[\'message\']) ) {
$name = $_POST[\'name\'];
$mail = $_POST[\'mail\'];
$message = nl2br($_POST[\'message\']);
$to = "[email protected]";
$from = $mail;
$subject = \'Kontaktformulär från emcolsson.se ifyllt\';
$message = \'<b>Name:</b> \'.$name.\' <br><b>Email:</b> \'.$mail.\' <p>\'.$message.\'</p>\';
$headers = "From: $from\\n";
$headers .= "MIME-version: 1.0\\n";
$headers .= "Content-Type: text/html; charset=utf-8\\n"; //Fixes ÅÄÖ in Sender name and Message
if( mail($to, \'=?UTF-8?B?\'.base64_encode($subject).\'?=\', $message, $headers) ) { //Fixes ÅÄÖ in subject
echo "success";
} else {
echo "The server failed to send the message. Please try again later.";
}
}
联系人表单。js公司:
function _(id) {
return document.getElementById(id); //makes _ a shortcode for document.getElementById(id)
}
function submitForm() {
_("submitButton").disabled = true; //User cant click submit many times and resend form data, after first click its disabled.
_("status").innerHTML = \'please wait...\'; //Gives span value and the user an indication of that data is being processed.
var formdata = new FormData(); // Creates variable that fetches they key value pair of id and value of the form inputs.
formdata.append( "name", _("name").value );
formdata.append( "mail", _("mail").value );
formdata.append( "message", _("message").value );
var ajax = new XMLHttpRequest(); // creating an ajax variable which is a XMLHttpRequest, opens it/fires it by posting the formdata to parser.php
ajax.open( "POST", "parser.php" );
ajax.onreadystatechange = function() { //when ready do this function
if(ajax.readyState == 4 && ajax.status == 200) { //when data is finished processing by php and data is returned by php to this ajax object(XMLHttpRequest)
if(ajax.responseText == "success") {
_("contact-form").innerHTML = \'<h2>Thanks for contacting me \'+_("name").value+\' I will get back to you as soon as possible.</h2>\';
_("status").innerHTML = ajax.responseText;
} else {
_("status").innerHTML = ajax.responseText;
_("submitButton").disabled = false;
clearForm();
}
}
}
ajax.send( formdata );
}
功能。php
wp_enqueue_script( \'contactform\', get_template_directory_uri() . \'/js/contactform.js\', array( \'jquery\' ), 1.1, true );
include_once( get_template_directory() . \'/includes/parser.php\' );