我正在尝试修改wordpress插件,以使用admin-ajax.php添加电子邮件发送功能,我在my_plugin.php中的代码如下:
add_action( 'wp_ajax_nopriv_send_email', 'send_email' );
add_action( 'wp_ajax_send_email', 'send_email' );
function send_email(){
echo "send email"; die(); //it could not printed
if ( count($_POST) > 0 ){
$to = $_REQUEST['to'];
$from = $_REQUEST['from'];
$sub = $_REQUEST['subject'];
$msg = $_REQUEST['msg'];
$headers = 'From: myname <myemail@wordpress.com>' . "rn";
wp_mail( $to, $sub, $msg, $headers);
exit;
}
exit;
}
在我的表格中.php
jQuery.ajax({
type: 'POST',
url: '".admin_url('admin-ajax.php')."',
action:'send_email',
data: { to:'reciever@gmail.com',
from: 'sender@gmail.com',
subject: 'test',
msg: 'thank you'
},
success: function (res) {
alert('The server responded: ' + res);
}
});
问题是,当我发布请求时,它无法进入send_email()函数,也不发送任何电子邮件,但它总是响应0,并抛出类似"服务器响应:0"的成功消息警报;我在这儿干什么?我被困在这里了。。
问题出在"action"参数上。它应该是"数据"的一部分:
jQuery.ajax({
type: 'POST',
url: '".admin_url('admin-ajax.php')."',
data: {
action:'send_email',
to:'reciever@gmail.com',
from: 'sender@gmail.com',
subject: 'test',
msg: 'thank you'
},
success: function (res) {
alert('The server responded: ' + res);
}
});