简体   繁体   English

Wordpress:如何使用ajax调用调用插件函数?

[英]Wordpress: how to call a plugin function with an ajax call?

I'm writing a Wordpress MU plugin, it includes a link with each post and I want to use ajax to call one of the plugin functions when the user clicks on this link, and then dynamically update the link-text with output from that function. 我正在编写一个Wordpress MU插件,它包含每个帖子的链接,我想在用户点击此链接时使用ajax调用其中一个插件函数,然后使用该函数的输出动态更新链接文本。

I'm stuck with the ajax query. 我坚持使用ajax查询。 I've got this complicated, clearly hack-ish, way to do it, but it is not quite working. 我有这种复杂的,明显是黑客的方式,但它不是很有效。 What is the 'correct' or 'wordpress' way to include ajax functionality in a plugin? 在插件中包含ajax功能的'正确'或'wordpress'方式是什么?

(My current hack code is below. When I click the generate link I don't get the same output I get in the wp page as when I go directly to sample-ajax.php in my browser.) (我当前的黑客代码如下。当我点击生成链接时,我没有得到与wp页面相同的输出,就像我在浏览器中直接访问sample-ajax.php一样。)

I've got my code[1] set up as follows: 我的代码[1]设置如下:

mu-plugins/sample.php: MU-插件/ sample.php:

<?php
/*
Plugin Name: Sample Plugin
*/
if (!class_exists("SamplePlugin")) {
  class SamplePlugin {
    function SamplePlugin() {}
    function addHeaderCode() {
      echo '<link type="text/css" rel="stylesheet" href="'.get_bloginfo('wpurl').
             '/wp-content/mu-plugins/sample/sample.css" />\n';
      wp_enqueue_script('sample-ajax', get_bloginfo('wpurl') .
             '/wp-content/mu-plugins/sample/sample-ajax.js.php',
             array('jquery'), '1.0');

    }
    // adds the link to post content.
    function addLink($content = '') {
        $content .= "<span class='foobar clicked'><a href='#'>click</a></span>";
        return $content;
    }
    function doAjax() { //
        echo "<a href='#'>AJAX!</a>";
    } 
  }
}
if (class_exists("SamplePlugin")) {
  $sample_plugin = new SamplePlugin();
}
if (isset($sample_plugin)) {
  add_action('wp_head',array(&$sample_plugin,'addHeaderCode'),1);
  add_filter('the_content', array(&$sample_plugin, 'addLink'));
}

mu-plugins/sample/sample-ajax.js.php: MU-插件/样品/试样ajax.js.php:

<?php
if (!function_exists('add_action')) {
    require_once("../../../wp-config.php");
}
?>
jQuery(document).ready(function(){
    jQuery(".foobar").bind("click", function() {
        var aref = this;
        jQuery(this).toggleClass('clicked');
        jQuery.ajax({
          url: "http://mysite/wp-content/mu-plugins/sample/sample-ajax.php",
          success: function(value) {
            jQuery(aref).html(value);
          }
        });
    });
});

mu-plugins/sample/sample-ajax.php: MU-插件/样品/试样ajax.php:

<?php
if (!function_exists('add_action')) {
  require_once("../../../wp-config.php");
}
if (isset($sample_plugin)) {
  $sample_plugin->doAjax();
} else {
  echo "unset";
}
?>

[1] Note: The following tutorial got me this far, but I'm stumped at this point. [1]注意:以下教程让我​​走到了这一步,但是我很难过。 http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin

TheDeadMedic is not quite right. TheDeadMedic不太对劲。 WordPress has built in AJAX capabilities. WordPress内置了AJAX功能。 Send your ajax request to /wp-admin/admin-ajax.php using POST with the argument 'action': 使用带参数'action'的POST将您的ajax请求发送到/wp-admin/admin-ajax.php:

jQuery(document).ready(function(){
    jQuery(".foobar").bind("click", function() {
        jQuery(this).toggleClass('clicked');
        jQuery.ajax({
          type:'POST',
          data:{action:'my_unique_action'},
          url: "http://mysite/wp-admin/admin-ajax.php",
          success: function(value) {
            jQuery(this).html(value);
          }
        });
    });
});

Then hook it in the plugin like this if you only want it to work for logged in users: 然后将它挂在插件中,如果你只想让它对登录的用户起作用:

add_action('wp_ajax_my_unique_action',array($sample_plugin,'doAjax'));

or hook it like this to work only for non-logged in users: 或者像这样挂钩它只适用于未登录的用户:

add_action('wp_ajax_nopriv_my_unique_action',array($sample_plugin,'doAjax'));

Use both if you want it to work for everybody. 如果你想让它适合每个人,请同时使用它们。

admin-ajax.php uses some action names already, so make sure you look through the file and don't use the same action names, or else you'll accidentally try to do things like delete comments, etc. admin-ajax.php已经使用了一些动作名称,因此请确保查看该文件并且不要使用相同的动作名称,否则您将不小心尝试删除注释等操作。

EDIT 编辑

Sorry, I didn't quite understand the question. 对不起,我不太明白这个问题。 I thought you were asking how to do an ajax request. 我以为你在问如何做一个ajax请求。 Anyway, two things I'd try: 无论如何,我要尝试两件事:

First, have your function echo just the word AJAX without the a tag. 首先,让你的函数只回显没有a标签的AJAX这个词。 Next, try changing your ajax call so it has both a success and a complete callback: 接下来,尝试更改您的ajax调用,以便它既有成功又有完整的回调:

jQuery(document).ready(function(){
    jQuery(".foobar").bind("click", function() {
        var val = '';
        jQuery(this).toggleClass('clicked');
        jQuery.ajax({
          type:'POST',
          data:{action:'my_unique_action'},
          url: "http://mysite/wp-admin/admin-ajax.php",
          success: function(value) {
            val = value;
          },
          complete: function(){
            jQuery(this).html(val);
          }
        });
    });
});

WordPress environment WordPress环境

First of all, in order to achieve this task, it's recommended to register then enqueue a jQuery script that will push the request to the server. 首先,为了完成这项任务,建议注册然后将jQuery脚本排入队列,将脚本推送到服务器。 These operations will be hooked in wp_enqueue_scripts action hook. 这些操作将挂钩在wp_enqueue_scripts动作钩子中。 In the same hook you should put wp_localize_script that it's used to include arbitrary Javascript. 在同一个钩子中你应该把它用于包含任意Javascript的wp_localize_script By this way there will be a JS object available in front end. 通过这种方式,前端将有一个JS对象。 This object carries on the correct url to be used by the jQuery handle. 该对象继续使用jQuery句柄使用的正确url。

Please take a look to: 请看看:

  1. wp_register_script(); wp_register_script(); function 功能
  2. wp_enqueue_scripts hook wp_enqueue_scripts挂钩
  3. wp_enqueue_script(); wp_enqueue_script(); function 功能
  4. wp_localize_script(); wp_localize_script(); function 功能

File: functions.php 1/2 文件:functions.php 1/2

add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' );
function so_enqueue_scripts(){
  wp_register_script( 'ajaxHandle', get_template_directory() . 'PATH TO YOUR JS FILE', array(), false, true );
  wp_enqueue_script( 'ajaxHandle' );
  wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

File: jquery.ajax.js 文件:jquery.ajax.js

This file makes the ajax call. 该文件进行ajax调用。

jQuery(document).ready( function($){
  //Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
  $.ajax({
    url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
    type: 'POST',
    data:{
      action: 'myaction', // this is the function in your functions.php that will be triggered
      name: 'John',
      age: '38'
    },
    success: function( data ){
      //Do something with the result from server
      console.log( data );
    }
  });
});

File: functions.php 2/2 文件:functions.php 2/2

Finally on your functions.php file there should be the function triggered by your ajax call. 最后在你的functions.php文件中应该有你的ajax调用触发的函数。 Remember the suffixes: 记住后缀:

  1. wp_ajax ( allow the function only for registered users or admin panel operations ) wp_ajax(仅允许注册用户或管理面板操作的功能)
  2. wp_ajax_nopriv ( allow the function for no privilege users ) wp_ajax_nopriv(允许无特权用户的功能)

These suffixes plus the action compose the name of your action: 这些后缀加上操作组成了您的操作名称:

wp_ajax_myaction or wp_ajax_nopriv_myaction wp_ajax_myactionwp_ajax_nopriv_myaction

add_action( 'wp_ajax_myaction', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so_wp_ajax_function' );
function so_wp_ajax_function(){
  //DO whatever you want with data posted
  //To send back a response you have to echo the result!
  echo $_POST['name'];
  echo $_POST['age'];
  wp_die(); // ajax call must die to avoid trailing 0 in your response
}

Hope it helps! 希望能帮助到你!

Let me know if something is not clear. 如果有什么不清楚,请告诉我。

Just to add an information. 只是为了添加信息。 If you want to receive an object from a php class method function : 如果你想从php类方法函数接收一个对象:

js file js文件

jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
    var data = {
        'action': 'getAllOptionsByAjax',
        'arg1': 'val1',
        'arg2': $(this).val() 
    };
    jQuery.post( ajaxurl, data, function(response) {
       var jsonObj = JSON.parse( response );
    });
});

php file php文件

public static function getAllOptionsByAjax(){

    global $wpdb;

    // Start query string
    $query_string  =  "SELECT * FROM wp_your_table WHERE col1='" . $_POST['arg1'] . "' AND col2 = '" . $_POST['arg2'] . "' ";

    // Return results
    $a_options = $wpdb->get_results( $query_string, ARRAY_A );
    $f_options = array();
    $f_options[null] =  __( 'Please select an item', 'my_domain' );
    foreach ($a_options as $option){
        $f_options [$option['id']] = $option['name'];
    }
    $json = json_encode( $f_options );
    echo $json;
    wp_die();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM