douhezhan5348
2014-03-22 15:18
浏览 191
已采纳

使用admin-ajax.php的AJAX请求

I'm trying to do an AJAX request in an WordPress plugin. The request is initiated on the front page embedded in an article using a custom shortcode.

I tried to combine infos from the documentation and this tutorial.

However something is going wrong when testing that method... the AJAX query hook isn't called.

This is how my page.php script is called for short code delivery:

add_shortcode('testshortcode', 'TestShortCodeFunction');

function TestShortCodeFunction($attributes)
{
   ob_start();
   include(__DIR__.'/page.php');
   return ob_get_clean();
}

This is my compacted test script page.php:

<?php

    add_action('wp_ajax_test', 'Test');
    add_action('wp_ajax_nopriv_test', 'Test');

    // do_action('wp_ajax_nopriv_test'); this calls Test()

    function Test()
    {
        echo 'Hallo';
        die();
    }
?>

<script type='text/javascript'>

    jQuery(document).ready(function() {

        console.log("JS query started");

        // The following does not call test()
        jQuery.ajax({
            type: "POST",
            url: "http://127.0.0.1/wordpress/wp-admin/admin-ajax.php?action=test",
            success: function(data) {
                console.log("Query returned: "+data);
            }
        });

    });

</script>

Output on the console is:

JS query started
Query returned: 0 

The Test() function is never call according to the PHP debugger.

The admin-ajax.php is executed according to the network monitor (URL http://127.0.0.1/wordpress/wp-admin/admin-ajax.php?action=test) but returns 0.

Inside admin-ajax.php do_action('wp_ajax_test') is called according to the PHP debugger.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试在WordPress插件中执行AJAX请求。 该请求是使用自定义短代码在文章中嵌入的首页上启动的。

我尝试组合来自文档本教程

但是在测试该方法时会出现问题......不会调用AJAX查询挂钩。< / p>

这是我的 page.php 脚本调用短代码的方式:

  add_shortcode('testshortcode  ','TestShortCodeFunction'); 
 
function TestShortCodeFunction($ attributes)
 {
 ob_start(); 
 include(__ DIR __。'/ page.php'); 
返回ob_get_clean(); 
} \  n   
 
 

这是我的压缩测试脚本 page.php

 &lt;?  php 
 
 add_action('wp_ajax_test','Test'); 
 add_action('wp_ajax_nopriv_test','Test'); 
 
 // do_action('wp_ajax_nopriv_test'  ); 这会调用Test()
 
函数Test()
 {
 echo'Hallo'; 
 die(); 
} 
?&gt; 
 
&lt; script type ='text / javascript'  &gt; 
 
 jQuery(document).ready(function(){
 
 console.log(“JS query started”); 
 
 //以下不调用test()
 jQuery。  ajax({
 type:“POST”,
 url:“http://127.0.0.1/wordpress/wp-admin/admin-ajax.php?action=test",
 success:function(data){  
 console.log(“查询返回:”+数据); 
} 
}); 
 
}); 
 
&lt; / script&gt; 
   
  
 

控制台上的输出是:

  JS查询已启动
Query返回:0 
   
 
 

Test()函数永远不会根据PHP调试器调用。

admin-ajax.php 是根据 网络监视器( URL http://127.0.0.1/wordpress/wp-admin/admin-ajax.php?action=test )但返回 0

内部 admin-ajax.php < 根据PHP调试器调用/ code> do_action('wp_ajax_test')

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题