我已将此模板转换为WordPress主题。一切都很顺利,除了我无法在contact_me.js部分获得 AJAX 请求的正确 url。
$.ajax({
url: "././mail/contact_me.php",
type: "POST",
data: {
name: name,
phone: phone,
email: email,
message: message
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
})
},
我知道这与WordPress中文件的引用方式有关。在 HTML 中添加 js 文件时,我做了类似的事情,但我不确定如何在 js 文件中处理它。
编辑:也许我必须将 contact_me.php 中的代码添加到函数中的 ajax 回调中.php?
编辑 2这是我的send_form,它似乎没有发送任何邮件。
function send_feedback(){
// Check for empty fields
if(empty($_POST['email']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$email_address = $_POST['email'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'xyz@mydomain.io'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Demo Feedback Form: $email_address";
$email_body = "You have received a new message from your demo feedback form.'n'n"."Here are the details:'n'nEmail: $email_address'n'nMessage:'n$message";
$headers = "From: noreply@mydomain.io'n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
}
add_action('wp_ajax_nopriv_send_feedback', 'send_feedback');
add_action('wp_ajax_send_feedback', 'send_feedback');
添加标题.php
<script>var ajaxURL = '<?php echo esc_js(admin_url('admin-ajax.php'));?>';</script>
添加您的网址:ajaxURL
在您的情况下
$.ajax({
url: ajaxURL,
type: "POST",
data: {
action: 'send_form',
name: name,
phone: phone,
email: email,
message: message
},
在您的函数中.php
function send_form(){
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$message = $_POST['message'];
//Do your send mail function etc.
wp_die();
}
add_action('wp_ajax_nopriv_send_form', 'send_form');
add_action('wp_ajax_send_form', 'send_form');