duanshan7261 2018-01-17 19:38
浏览 44
已采纳

在Wordpress中:使用AJAX发布jQuery变量,以便以后在PHP中使用

In WordPress, I'm trying to post a jQuery variable using AJAX to use later in PHP. I've setup my jQuery function and the function to echo the variable.

I am getting the success message from the jQuery function in the console log, but the $_POST variable is null.

Below are the functions I've setup:

function foo_carousel_js() { ?>
     <script>
     jQuery(document).ready(function($) {
       var ajax_url = "<?php echo admin_url('admin-ajax.php'); ?>";
       var count_ci = $('.selector li').length;

       $.ajax({
          type: 'POST',   
          url: ajax_url,  
          data: {
            action : 'foo_item_count',
            count_ci : count_ci
          },
          success:function( data ) {
            console.log( data );
          }
       });
    });
   </script>
<?php }
add_action( 'wp_footer', 'foo_carousel_js' );

function foo_item_count() {

    $k = esc_html( $_POST['count_ci'] );
    echo $k;

    wp_die(); 
}
add_action('wp_ajax_foo_item_count', 'foo_item_count');
add_action('wp_ajax_nopriv_foo_item_count', 'foo_item_count');
  • 写回答

1条回答 默认 最新

  • dongsuiying7773 2018-01-17 21:18
    关注

    I had the exact same question/problem a few years ago. Turns out you cannot access that Ajax sent value anywhere else within WP besides your functions.php and of course plugin files. Reason being that while doing Ajax, WP only reloads the mentioned files (functions and plugins) but not the rest of the template structure. Therefore, while $_POST has your data, you can't render it on a template file because those are already loaded.

    Edit:

    Even within the plugin files, you only have access to your $_POST values within an Ajax handler function.

    I recommend rethinking your goal, maybe Ajax isn't the way to go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传
  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决