javascript - Ajax 无法在 WordPress 插件短代码的前端工作

标签 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]

最佳答案

在将脚本排入队列之前,您需要先对其进行本地化,而且您当前正在对 my-script 进行入队时本地化 script-name

试试这个:

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')
        }

关于javascript - Ajax 无法在 WordPress 插件短代码的前端工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24691676/

相关文章:

javascript - .each() 和 eval() 的问题

javascript - WebPack:如何访问单独的类/文件中所需的依赖项

javascript - 使用 jquery 修改自定义 HTML-Attribute 不会影响 CSS

php - 使用 jQuery : Is 'https' enough to secure the XML? 从 PHP webservice 调用解析 XML

javascript - PHP 变量在 JS 中不起作用

javascript - 如何在 IE 7 和 6 中通过类名获取元素

jquery - :contain/start by

javascript - 在自定义 AngularJS 指令中使用 $timeout

javascript - 未解析的符号 : llvm_trap from Emscripten

php - 从 while 循环加载变量