我正在写一个wordpress MU插件,它包含每个帖子的链接,当用户点击此链接时,我想使用ajax调用插件函数之一,然后使用该函数的输出动态更新链接文本.
我遇到了ajax查询.我有这个复杂的,清楚的黑客,这样做,但它不是很有效.在插件中包含ajax功能的“正确”或“wordpress”方式是什么?
(我当前的hack代码在下面,当我点击生成链接,我没有得到相同的输出,我进入wp页面,当我直接去我的浏览器中的sample-ajax.PHP.)
我有我的代码[1]设置如下:
- <?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','addLink'));
- }
- <?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);
- }
- });
- });
- });
- <?PHP
- if (!function_exists('add_action')) {
- require_once("../../../wp-config.php");
- }
- if (isset($sample_plugin)) {
- $sample_plugin->doAjax();
- } else {
- echo "unset";
- }
- ?>
[1]注意:以下教程让我很远,但在这一点上我很失望.
http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin
TheDeadMedic是不对的. wordpress内置AJAX功能.发送你的ajax请求到/wp-admin/admin-ajax.PHP使用POST与参数’action’:
- 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);
- }
- });
- });
- });
- add_action('wp_ajax_my_unique_action',array($sample_plugin,'doAjax'));
- add_action('wp_ajax_nopriv_my_unique_action','doAjax'));
如果您希望它适用于所有人,请同时使用.
admin-ajax.PHP已经使用了一些动作名称,所以请确保您查看文件,不要使用相同的动作名称,否则您会意外地尝试删除注释等.
编辑
对不起,我不太明白这个问题.我以为你在问如何做一个ajax请求.无论如何,我会尝试两件事情:
首先,让你的函数只返回AJAX这个字,而不用标记.接下来,尝试更改您的ajax调用,以便其成功和完整的回调:
- jQuery(document).ready(function(){
- jQuery(".foobar").bind("click",function() {
- var val = '';
- jQuery(this).toggleClass('clicked');
- jQuery.ajax({
- type:'POST',success: function(value) {
- val = value;
- },complete: function(){
- jQuery(this).html(val);
- }
- });
- });
- });