如何在 Wordpress 中加载 Ajax [英] How to Load Ajax in Wordpress

查看:62
本文介绍了如何在 Wordpress 中加载 Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我熟悉在 jQuery 中以普通方式使用 ajax.
我已经玩了一段时间了,但不明白 Wordpress 需要什么才能让它工作......
我这里的内容取自一些教程或文章.
这是在 functions.php 中(在子主题中):

I'm familiar with using ajax in the ordinary way with jQuery.
I've played around it for a while, but don't understand what Wordpress needs to get it to work...
What I have here is taken from some tutorial or article.
This is in functions.php (in a child theme):

// code to load jquery - working fine

// code to load javascript file - working fine

// ENABLE AJAX :
function add_ajax()
{
   wp_localize_script(
    'function',
    'ajax_script',
    array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

$dirName = get_stylesheet_directory();  // use this to get child theme dir
require_once ($dirName."/ajax.php");  

add_action("wp_ajax_nopriv_function1", "function1"); // function in ajax.php

add_action('template_redirect', 'add_ajax');  

jQuery 本身正在加载并且工作正常.

The jQuery itself is loading and working fine.

我尝试了一些基本的ajax,如下所示:

I have tried some basic ajax like the following:

jQuery(document).ready(function($){
    $('a.link').click(function(){
        $.ajax({
              url:     ajax_script.ajaxurl,
              data:    ({action  : 'function1'}),
              success: function(data){
                     $('#result').html(data);
              }
        });
        return false;
    });
});   

除此之外,我不知道如何测试以查看它是否正确加载...

Besides this, I don't know how I can test to see if it's even loaded correctly to begin with...

这里的任何帮助将不胜感激.

Any help here would be appreciated.


在萤火虫这个错误:


In firebug this error:

ReferenceError: ajax_script is not defined
       url:   ajax_script.ajaxurl,

推荐答案

根据您的要求,我已将其作为您的答案.

As per your request I have put this in an answer for you.

正如 Hieu Nguyen 在他的回答中所建议的,您可以使用 ajaxurl javascript 变量来引用 admin-ajax.php 文件.但是这个变量没有在前端声明.通过将以下内容放在主题的 header.php 中,在前端声明这一点很简单.

As Hieu Nguyen suggested in his answer, you can use the ajaxurl javascript variable to reference the admin-ajax.php file. However this variable is not declared on the frontend. It is simple to declare this on the front end, by putting the following in the header.php of your theme.

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

正如 Wordpress AJAX 文档中所述,您有两个不同的钩子 - wp_ajax_(action),和 wp_ajax_nopriv_(action).它们之间的区别是:

As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:

  • wp_ajax_(action):如果从管理面板内部进行 ajax 调用,则会触发此操作.
  • wp_ajax_nopriv_(action):如果 ajax 调用是从网站前端进行的,则会触发此操作.

上面链接的文档中描述了其他所有内容.快乐编码!

Everything else is described in the documentation linked above. Happy coding!

附言这是一个应该工作的例子.(我没有测试过)

P.S. Here is an example that should work. (I have not tested)

前端:

<script type="text/javascript">
    jQuery.ajax({
        url: ajaxurl,
        data: {
            action: 'my_action_name'
        },
        type: 'GET'
    });
</script>

后端:

<?php
    function my_ajax_callback_function() {
        // Implement ajax function here
    }
    add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );    // If called from admin panel
    add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );    // If called from front end
?>

<小时>

更新尽管这是一个古老的答案,但它似乎不断得到人们的赞许——这太棒了!我认为这可能对某些人有用.


UPDATE Even though this is an old answer, it seems to keep getting thumbs up from people - which is great! I think this may be of use to some people.

WordPress 有一个函数 wp_localize_script.该函数将一组数据作为第三个参数,用于翻译,如下所示:

WordPress has a function wp_localize_script. This function takes an array of data as the third parameter, intended to be translations, like the following:

var translation = {
    success: "Success!",
    failure: "Failure!",
    error: "Error!",
    ...
};

所以这只是将一个对象加载到 HTML head 标签中.这可以通过以下方式使用:

So this simply loads an object into the HTML head tag. This can be utilized in the following way:

后端:

wp_localize_script( 'FrontEndAjax', 'ajax', array(
    'url' => admin_url( 'admin-ajax.php' )
) );

这种方法的优点是它可以在主题和插件中使用,因为您没有将 ajax URL 变量硬编码到主题中.

The advantage of this method is that it may be used in both themes AND plugins, as you are not hard-coding the ajax URL variable into the theme.

在前端,URL 现在可以通过 ajax.url 访问,而不是前面示例中的简单 ajaxurl.

On the front end, the URL is now accessible via ajax.url, rather than simply ajaxurl in the previous examples.

这篇关于如何在 Wordpress 中加载 Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆