将JavaScript变量转换为WordPress php变量

时间:2018-06-13 作者:Deyan Veselinov

我需要将js变量推入php变量。AJAX url是通过wp\\u localize\\u脚本设置的,但它返回错误400错误请求。功能。php看起来像

wp_localize_script( \'script-js\', \'compareids_ajax\', array( \'ajax_url\' => admin_url(\'admin-ajax.php\')) );
自定义。js公司

 var compareIDs = $(".table td input:checkbox:checked").map(function(){
          return $(this).val();
        }).get(); // <----
        $(\'.selected\').text(compareIDs);
        console.log(compareIDs);



             $.ajax({
                        type: "POST",

                        url: compareids_ajax.ajax_url,
                        data: \'{ compareIDs : compareIDs }\',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msg) {

                        },
                        error: function (errormessage) {

                        }
                    });
和我的筛选页面。php有

  <?php

                $compareIDs = array( $_POST[\'compareIDs\'] );


    $args02 = array( \'post_type\' => \'custom\',
                     \'post__in\' => $compareIDs );

    $loop02 = new WP_Query( $args02 );

    while ( $loop02->have_posts() ) : $loop02->the_post();
    ?>

2 个回复
最合适的回答,由SO网友:Bikash Waiba 整理而成

首先,您需要将函数名作为附加数据发送为

  $.ajax({
        type: "POST",
        url: compareids_ajax.ajax_url,
        data: {                             // Data object
              compareIDs : compareIDs,
              action: \'your_ajax_function\'  // This is required to let WordPress know which function to invoke
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
              console.log( msg );
        },
        error: function (errormessage) {
              console.log( errormessage );
        }
  });
在php文件中

  add_action(\'wp_ajax_nopriv_your_ajax_function\',\'your_ajax_function\'); // Ajax Function should be hooked like this for unauthenticated users
  add_action(\'wp_ajax_your_ajax_function\',\'your_ajax_function\'); // 

  function your_ajax_function(){

        $comparedIds = $_POST[\'compareIDs\']; // Your data is now available in $_POST 
       // Do your stuff here

    die(); // At the end 

  }
请参见wp_ajax_(action)

SO网友:Deyan Veselinov

非常感谢。我确实这样做了,但似乎与管理ajax没有任何联系。php总是400个错误请求。即使我只是用函数来测试它。php

          add_action(\'wp_ajax_my_action\', \'my_action\');

           function my_action(){

            echo \'My action\';

          }


   then enter http://my-website.com/wp-admin/admin-ajax.php?action=my_action
浏览器显示0

结束