douwei1174 2013-01-25 12:01
浏览 106
已采纳

使用wordpress处理ajax请求响应

i've done an ajax request in my wordpress plugin.My request is based on steps below:

1) i am including js file and starting a request document on ready

2)At the php side i want to take this request and print it to test.

for all these stuff i wrote these codes:

main.js:

 $(function(){      
    $.post('/wp-content/plugins/dsn/functions.php',{token:"1tibu4"},function(data) {
      console.log(data);
    },"json");
 });

functions.php:

 <?php 

   add_action('loop_end', 'init');

   function init(){
       global $_POST;

       $post= $_POST;   
       echo json_encode($post);Exit;

   }

My question is when request complete there is nothing on the response tab of console screen.How come this happen?

  • 写回答

2条回答 默认 最新

  • dsgk40568 2013-01-25 12:11
    关注

    WordPress has a unique way of handling AJAX. If you make a request to the php file directly, then you are not loading the rest of the WordPress framework and a lot of WordPress specific functionality will not be available to you.

    In the PHP side, what you have to do is use code that looks like this:

    //for logged in users
    add_action('wp_ajax_my_action', 'my_action_callback');
    //for not logged in users
    add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
    
    function my_action_callback() {
      //your function here
      exit; //always call exit at the end of a WordPress ajax function
    }
    

    In the JS side, you need to send your request to a file called "wp-admin/admin-ajax.php"

    So your request would look like this (using jQuery):

    $.ajax({
        url : '/wp-admin/admin-ajax.php',
        type : 'get', //or 'post'
        data : {
                    action: 'my_action_callback'
                }
    })
         .fail(function(r,status,jqXHR) {
             console.log('failed');
         });
         .done(function(r,status,jqXHR) {
            console.log('success');
         });
    

    Note the my_action_callback parts.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题