php 如何在 Wordpress 中加载 Ajax

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17710728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:18:41  来源:igfitidea点击:

How to Load Ajax in Wordpress

phpjqueryajaxwordpress

提问by grai

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 需要什么才能让它工作......
我这里的内容来自一些教程或文章。
这是在functions.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:

编辑:
在萤火虫这个错误:

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

回答by Shane

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 文件。但是这个变量没有在前端声明。通过将以下内容放在主题的 header.php 中,在前端声明这一点很简单。

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

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

正如Wordpress AJAX文档中所述,您有两个不同的钩子 - 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_nopriv_(action): This is fired if the ajax call is made from the front end of the website.
  • 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 shouldwork. (I have not tested)

PS这是一个应该工作的例子。(我没有测试过)

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
?>


UPDATEEven 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 ajaxurlin the previous examples.

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

回答by Hieu Nguyen

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

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

Secondly, ajax_scriptis 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 调试 ajax 调用,网络和控制台选项卡将是您的朋友。在PHP方面,print_r()还是var_dump()会是你的朋友。

回答by Jason Boerner

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。所以这是,因为 htaccess 在 wordpress 中不太可能,所以我执行以下操作。

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

1.在我的 wp-content 文件夹中的 htaccess 文件中,我将其添加到已经存在的内容下方

<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 - 您可以将它与所有其他文件(例如 header.php footer.php 等)一起放在 wp-content/themes/themeName 文件夹中...它就在您的主题中根。

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.

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

回答by Goran Jakovljevic

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 

回答by grai

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