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

使用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.

  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥20 有人知道怎么将vsi格式的图片文件,转换为svs格式的文件吗
      • ¥15 历史模拟法计算var实验报告
      • ¥15 白鲸算法优化K值的VMD分解出错
      • ¥20 写一个基于52单片机用hc-05蓝牙模块控制28BYJ-48步进电机进行旋转,在手机蓝牙串口输入1019电机转半圈,输入2038电机转一圈,输入0复位的代码吗
      • ¥15 求51单片机8位数码管计时器程序
      • ¥20 matlab识别螺母边缘
      • ¥15 python 6x6游戏加登录、记录系统
      • ¥100 基于做一个模拟智慧路灯
      • ¥15 ME21N 创建采购成功并且生成采购订单号,但显示“快件文档更新已取消”,SM13看错误提示为如下截图:
      • ¥30 android 集成fmod实现变声功能中遇到的问题