Ajax不在wordpress插件短代码的前端工作

时间:2014-07-11 06:50:24

标签: javascript php jquery ajax wordpress

这是我的wordpress插件代码

function my_action_callback() {
      check_ajax_referer( 'my-special-string', 'security' );

      $whatever = intval( $_POST['whatever'] );
      $whatever += 10;
      echo $whatever;
      die(); 
    }
    add_action( 'wp_ajax_my_action', 'my_action_callback' );
    add_shortcode('my_products','my_shortcode');

        function my_shortcode($atts)
        {
            extract(shortcode_atts(array(
                'id'=>''       
            ), $atts));
         ob_start();

         wp_enqueue_script( 'my-script', plugins_url( 'myplugin/js/example.js' ), array('jquery'), NULL, true);
         wp_localize_script( 'script-name', 'MyAjax', array(
             'ajaxurl' => admin_url( 'admin-ajax.php' ),
             'security' => wp_create_nonce( 'my-special-string' )
          ));
        }

example.js 代码

jQuery(document).ready(function($) {

  var data = {
    action: 'my_action',
    security : MyAjax.security,
    whatever: 1234
  };

  $.post(MyAjax.ajaxurl, data, function(response) {
    alert('Got this from the server: ' + response);
  });
});

它不会提醒任何值。为什么? 我的短代码 [my_products]

1 个答案:

答案 0 :(得分:0)

您需要先将脚本本地化,然后才能将其排入队列,同时您还要在script-name入队时my-script进行本地化。

试试这个:

function my_shortcode($atts)
        {
            extract(shortcode_atts(array(
                'id'=>''       
            ), $atts));
         ob_start();
         // Register the script first.
         wp_register_script( 'script-name', plugins_url( 'myplugin/js/example.js' ), array('jquery'), NULL, true);
         // Now localize it.
         wp_localize_script( 'script-name', 'MyAjax', array(
             'ajaxurl' => admin_url( 'admin-ajax.php' ),
             'security' => wp_create_nonce( 'my-special-string' )
          ));
          // Now enqueue the script
          wp_enqueue_script( 'script-name')
        }