如何在Wordpress中加载Ajax

时间:2021-09-25 19:18:43

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):

我熟悉使用jQuery的普通方式使用ajax。我已经考虑了一段时间,但是不明白Wordpress需要什么来让它工作……我这里的内容是从一些教程或文章中摘录的。这是在功能。php(子主题):

// 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');  

The jQuery itself is loading and working fine.

jQuery本身正在加载并运行良好。

I have tried some basic ajax like the following:

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

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.

如有任何帮助,我们将不胜感激。

EDIT:
In firebug this error:

编辑:在firebug中:

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

5 个解决方案

#1


42  

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

我已按你的要求给你答复了。

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.

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

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

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:

正如在Wordpress AJAX文档中所描述的,您有两个不同的hook—wp_ajax_(action)和wp_ajax_nopriv_(action)。它们之间的区别是:

  • wp_ajax_(action): This is fired if the ajax call is made from inside the admin panel.
  • wp_ajax_(操作):如果ajax调用来自管理面板,则会触发此操作。
  • wp_ajax_nopriv_(action): This is fired if the ajax call is made from the front end of the website.
  • wp_ajax_nopriv_(动作):如果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)

这里有一个例子。(我没有测试)

Front end:

前端:

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

Back end:

后端:

<?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 has a function wp_localize_script. This function takes an array of data as the third parameter, intended to be translations, like the following:

WordPress有一个函数wp_localize_script。此函数以数据数组作为第三个参数,目的是转换,如下所示:

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

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

因此,这只需要将一个对象加载到HTML head标记中。这可以用下列方式加以利用:

Backend:

后端:

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

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.

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

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

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

#2


7  

Firstly, you should read this page thoroughly http://codex.wordpress.org/AJAX_in_Plugins

首先,您应该彻底阅读这个页面http://codex.wordpress.org/AJAX_in_Plugins

Secondly, ajax_script is not defined so you should change to: url: ajaxurl. I don't see your function1() in the above code but you might already define it in other file.

其次,没有定义ajax_script,所以应该更改为:url: ajaxurl。我在上面的代码中没有看到function1(),但是您可能已经在其他文件中定义了它。

And finally, learn how to debug ajax call using Firebug, network and console tab will be your friends. On the PHP side, print_r() or var_dump() will be your friends.

最后,学习如何使用Firebug、network和console选项卡调试ajax调用。在PHP方面,print_r()或var_dump()将是您的朋友。

#3


2  

Personally i prefer to do ajax in wordpress the same way that i would do ajax on any other site. I create a processor php file that handles all my ajax requests and just use that URL. So this is, because of htaccess not exactly possible in wordpress so i do the following.

我个人更喜欢在wordpress中使用ajax,就像我在其他网站上使用ajax一样。我创建了一个处理器php文件,它处理所有的ajax请求,并使用该URL。这是因为在wordpress中htaccess是不可能的,所以我做了如下的操作。

1.in my htaccess file that lives in my wp-content folder i add this below what's already there

1。在我的htaccess文件中,在我的wp-content文件夹中,我在下面添加了这个

<FilesMatch "forms?\.php$">
Order Allow,Deny
Allow from all
</FilesMatch>

In this case my processor file is called forms.php - you would put this in your wp-content/themes/themeName folder along with all your other files such as header.php footer.php etc... it just lives in your theme root.

在本例中,我的处理器文件称为forms。php -你可以把它放在你的wp-content/theme /themeName文件夹中,以及所有其他文件,如header。php页脚。php等等……它只存在于你的主题根中。

2.) In my ajax code i can then use my url like this

2)。在ajax代码中,我可以像这样使用url

$.ajax({
    url:'/wp-content/themes/themeName/forms.php',
    data:({
        someVar: someValue
    }),
    type: 'POST'
});

obviously you can add in any of your before, success or error type things you'd like ...but yea this is (i believe) the easier way to do it because you avoid all the silliness of telling wordpress in 8 different places what's going to happen and this also let's you avoid doing other things you see people doing where they put js code on the page level so they can dip into php where i prefer to keep my js files separate.

显然,你可以添加任何你以前,成功或错误类型的东西你想……但是的(我相信),这是更简单的方法去做因为你避免愚蠢的告诉wordpress在8个不同的地方会发生什么,这也让你避免做其他事情你看到人们做他们把js代码在页面级别,这样他们就可以动用php,我宁愿让我的js文件分开。

#4


2  

Use wp_localize_script and pass url there:

使用wp_localize_script并在那里传递url:

wp_localize_script( some_handle, 'admin_url', array('ajax_url' => admin_url( 'admin-ajax.php' ) ) );

then inside js, you can call it by

然后在js内部,你可以调用它

admin_url.ajax_url 

#5


-2  

I thought that since the js file was already loaded, that I didn't need to load/enqueue it again in the separate add_ajax function.
But this must be necessary, or I did this and it's now working.

我认为,由于已经加载了js文件,所以不需要在单独的add_ajax函数中再次加载/加入队列。但这必须是必要的,否则我就这么做了,现在开始工作了。

Hopefully will help someone else.

希望能帮助别人。

Here is the corrected code from the question:

以下是问题中的修正代码:

// code to load jquery - working fine

// code to load javascript file - working fine

// ENABLE AJAX :
function add_ajax()
{
    wp_enqueue_script(
       'function',
       'http://host/blog/wp-content/themes/theme/js.js',
       array( 'jquery' ),
       '1.0',
       1
   );

   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');  

#1


42  

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

我已按你的要求给你答复了。

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.

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

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

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:

正如在Wordpress AJAX文档中所描述的,您有两个不同的hook—wp_ajax_(action)和wp_ajax_nopriv_(action)。它们之间的区别是:

  • wp_ajax_(action): This is fired if the ajax call is made from inside the admin panel.
  • wp_ajax_(操作):如果ajax调用来自管理面板,则会触发此操作。
  • wp_ajax_nopriv_(action): This is fired if the ajax call is made from the front end of the website.
  • wp_ajax_nopriv_(动作):如果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)

这里有一个例子。(我没有测试)

Front end:

前端:

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

Back end:

后端:

<?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 has a function wp_localize_script. This function takes an array of data as the third parameter, intended to be translations, like the following:

WordPress有一个函数wp_localize_script。此函数以数据数组作为第三个参数,目的是转换,如下所示:

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

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

因此,这只需要将一个对象加载到HTML head标记中。这可以用下列方式加以利用:

Backend:

后端:

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

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.

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

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

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

#2


7  

Firstly, you should read this page thoroughly http://codex.wordpress.org/AJAX_in_Plugins

首先,您应该彻底阅读这个页面http://codex.wordpress.org/AJAX_in_Plugins

Secondly, ajax_script is not defined so you should change to: url: ajaxurl. I don't see your function1() in the above code but you might already define it in other file.

其次,没有定义ajax_script,所以应该更改为:url: ajaxurl。我在上面的代码中没有看到function1(),但是您可能已经在其他文件中定义了它。

And finally, learn how to debug ajax call using Firebug, network and console tab will be your friends. On the PHP side, print_r() or var_dump() will be your friends.

最后,学习如何使用Firebug、network和console选项卡调试ajax调用。在PHP方面,print_r()或var_dump()将是您的朋友。

#3


2  

Personally i prefer to do ajax in wordpress the same way that i would do ajax on any other site. I create a processor php file that handles all my ajax requests and just use that URL. So this is, because of htaccess not exactly possible in wordpress so i do the following.

我个人更喜欢在wordpress中使用ajax,就像我在其他网站上使用ajax一样。我创建了一个处理器php文件,它处理所有的ajax请求,并使用该URL。这是因为在wordpress中htaccess是不可能的,所以我做了如下的操作。

1.in my htaccess file that lives in my wp-content folder i add this below what's already there

1。在我的htaccess文件中,在我的wp-content文件夹中,我在下面添加了这个

<FilesMatch "forms?\.php$">
Order Allow,Deny
Allow from all
</FilesMatch>

In this case my processor file is called forms.php - you would put this in your wp-content/themes/themeName folder along with all your other files such as header.php footer.php etc... it just lives in your theme root.

在本例中,我的处理器文件称为forms。php -你可以把它放在你的wp-content/theme /themeName文件夹中,以及所有其他文件,如header。php页脚。php等等……它只存在于你的主题根中。

2.) In my ajax code i can then use my url like this

2)。在ajax代码中,我可以像这样使用url

$.ajax({
    url:'/wp-content/themes/themeName/forms.php',
    data:({
        someVar: someValue
    }),
    type: 'POST'
});

obviously you can add in any of your before, success or error type things you'd like ...but yea this is (i believe) the easier way to do it because you avoid all the silliness of telling wordpress in 8 different places what's going to happen and this also let's you avoid doing other things you see people doing where they put js code on the page level so they can dip into php where i prefer to keep my js files separate.

显然,你可以添加任何你以前,成功或错误类型的东西你想……但是的(我相信),这是更简单的方法去做因为你避免愚蠢的告诉wordpress在8个不同的地方会发生什么,这也让你避免做其他事情你看到人们做他们把js代码在页面级别,这样他们就可以动用php,我宁愿让我的js文件分开。

#4


2  

Use wp_localize_script and pass url there:

使用wp_localize_script并在那里传递url:

wp_localize_script( some_handle, 'admin_url', array('ajax_url' => admin_url( 'admin-ajax.php' ) ) );

then inside js, you can call it by

然后在js内部,你可以调用它

admin_url.ajax_url 

#5


-2  

I thought that since the js file was already loaded, that I didn't need to load/enqueue it again in the separate add_ajax function.
But this must be necessary, or I did this and it's now working.

我认为,由于已经加载了js文件,所以不需要在单独的add_ajax函数中再次加载/加入队列。但这必须是必要的,否则我就这么做了,现在开始工作了。

Hopefully will help someone else.

希望能帮助别人。

Here is the corrected code from the question:

以下是问题中的修正代码:

// code to load jquery - working fine

// code to load javascript file - working fine

// ENABLE AJAX :
function add_ajax()
{
    wp_enqueue_script(
       'function',
       'http://host/blog/wp-content/themes/theme/js.js',
       array( 'jquery' ),
       '1.0',
       1
   );

   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');