php Wordpress:如何使用 ajax 调用调用插件函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2908823/
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
Wordpress: how to call a plugin function with an ajax call?
提问by Bee
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. 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 查询困住了。我有这种复杂的,显然是hack-ish的方法,但它并不完全有效。在插件中包含 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.)
(我当前的 hack 代码如下。当我单击生成链接时,我在 wp 页面中获得的输出与在浏览器中直接转到 sample-ajax.php 时获得的输出不同。)
I've got my code[1] set up as follows:
我的代码[1]设置如下:
mu-plugins/sample.php:
mu-plugins/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-plugins/sample/sample-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-plugins/sample/sample-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. http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin
[1] 注意:下面的教程让我走到了这一步,但在这一点上我很难过。 http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin
回答by John P Bloch
TheDeadMedic is not quite right. WordPress has built in AJAX capabilities. Send your ajax request to /wp-admin/admin-ajax.php using POST with the argument 'action':
TheDeadMedic 不太对劲。WordPress 内置了 AJAX 功能。使用带有参数“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. Anyway, two things I'd try:
对不起,我不太明白这个问题。我以为你在问如何做一个ajax请求。无论如何,我会尝试两件事:
First, have your function echo just the word AJAX without the atag. Next, try changing your ajax call so it has both a success and a complete callback:
首先,让你的函数只回显没有a标签的AJAX 这个词。接下来,尝试更改您的 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);
}
});
});
});
回答by rams0610
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. These operations will be hooked in wp_enqueue_scriptsaction hook. In the same hook you should put wp_localize_scriptthat it's used to include arbitrary Javascript. By this way there will be a JS object available in front end. This object carries on the correct url to be used by the jQuery handle.
首先,为了完成这个任务,建议注册然后入队一个 jQuery 脚本,它将请求推送到服务器。这些操作将被钩在wp_enqueue_scripts动作钩子中。在同一个钩子中,您应该wp_localize_script指出它用于包含任意 Javascript。通过这种方式,前端就有一个可用的 JS 对象。该对象携带 jQuery 句柄使用的正确 url。
Please take a look to:
请看一看:
- wp_register_script();function
- wp_enqueue_scriptshook
- wp_enqueue_script();function
- 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. Remember the suffixes:
最后,在您的functions.php 文件中,应该有由您的ajax 调用触发的函数。记住后缀:
- wp_ajax ( allow the function only for registered users or admin panel operations )
- wp_ajax_nopriv ( allow the function for no privilege users )
- wp_ajax(仅允许注册用户或管理面板操作的功能)
- wp_ajax_nopriv ( 允许无权限用户的功能)
These suffixes plus the action compose the name of your action:
这些后缀加上动作构成了你的动作的名称:
wp_ajax_myactionor wp_ajax_nopriv_myaction
wp_ajax_myaction或者 wp_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.
如果有不清楚的地方,请告诉我。
回答by J.BizMai
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();
}

