13

我使用这个 jquery-ajax 脚本发送电子邮件:

    $.ajax({
        url: process.php,    
        type: "POST",
        data: data,        
        cache: false,
    ...

url我调用发送电子邮件的 php 文件中,但只有当我指定完整路径时,ajax 才会得到它:

url: "http://www.domain.com/wp-content/themes/site_theme/templates/process.php",

但我必须使用这样的语法:

url: "../../templates/process.php",

或使用变量在 html 页眉/页脚中声明

html

<script type="text/javascript">
  var urlMail = '<?php bloginfo('template_url'); ?>/templates/process.php';
</script>

脚本

url: "../../templates/process.php",

但是对于上述两种情况,浏览器控制台都会检索到此错误:

POST http://www.domain.com/templates/process.php 404 Not Found 1.56s

我哪里错了?

4

3 回答 3

27

这不是在 wordpress 中实现 ajax 的方式。所有 ajax 请求都应该发送到admin-ajax.php.

在您的模板文件中:

<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>

在你的 js 中:

$.ajax({
        url: ajaxurl,    
        type: "POST",
        cache: false,
        data: data + '&action=sendmail' //action defines which function to use in add_action
});

在你的functions.php中:

function send_my_mail(){
#do your stuff
}

add_action('wp_ajax_sendmail', 'send_my_mail');
add_action('wp_ajax_nopriv_sendmail', 'send_my_mail');

阅读有关Ajax in Plugins.

于 2013-04-29T09:21:04.680 回答
0

我建议您使用注册表之类的系统将所有“全局”值保存在一个地方。

注册表设计模式

如果您对此感兴趣,可以使用我的小型 jQuery 插件。GitHub 代表

<script type="text/javascript">
    $.Registry.set('urlMail', '<?php get_bloginfo('template_url'); ?>/templates/process.php';
</script>

要从注册表中获取价值,您必须使用 $.Registry.get('urlMail');

于 2013-04-29T09:13:18.687 回答
0

我已经使用RRikesh提供的代码解决了但替换

data: data 

data: data + '&action=sendmail'
于 2013-04-30T11:17:37.590 回答