doudeng2016 2018-05-16 06:05 采纳率: 0%
浏览 76
已采纳

为什么Javascript文件从php文件中获取空数组? Wordpress插件

I am creating the plugin that calculates income taxes. I don't need to reload page so I am going to use ajax. I need to get a plugin's path and transfer it to javascript file.

$my_data_array = [];

add_shortcode('penalty', 'penalty_calculator');
add_action( 'wp_enqueue_scripts', 'my_styles_scripts' );

function my_styles_scripts(){
    global $my_data_array;

    wp_register_script( 'my-js', plugins_url( 'js/my_functions.js', __FILE__ ), array('jquery'), '', true );

    wp_enqueue_script( 'my-js' );

    wp_localize_script( 'my-js', 'dataObj', $my_data_array );
}



function penalty_calculator(){
    global $my_data_array;

    $my_data_array= [
        'path' => plugin_dir_url(__FILE__)
    ];


    ?>

    <form action="" method="post" class="income_tax_calculator">

        <?php wp_nonce_field(); ?>

        <p>
            <label for="income_tax">How many charges are there?</label>
            <input type="text" name="income_tax" id="income_tax">
        </p>

        <p>
            <input type="submit" name="calculate_income_tax" id="calculate_income_tax" value="Calculate">
        </p>

    </form>

    <?php

}

my js file:

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

    console.log(dataObj)   // empty!

    $("#calculate_income_tax").click(function(event){

        event.preventDefault();

        var income_tax = $("#income_tax").val();

        // ajax, post, calculate.php is in plugin directory

    });

});

My javascript file get empty dataObj array from php file and I don't know why. I load my javascript file after jQuery, in the footer, but array is till empty. Javascript file is really found in the footer in view source code.

Generally, am I in a good way? This is my first plugin.

  • 写回答

1条回答 默认 最新

  • doucong1268 2018-05-16 13:20
    关注

    I needed to use this:

    add_action( 'wp_footer', 'my_styles_scripts' );
    

    not

    add_action( 'wp_enqueue_scripts', 'my_styles_scripts' );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 三向应力状态求剪应力
  • ¥15 jupyter notebook如何添加libGL.so.1库
  • ¥20 easyPoi能否实现下拉多选或者复选框
  • ¥15 网桥在转发帧时,会变帧的源地址和目的地址吗?
  • ¥15 用Multisim设计汽车尾灯控制电路
  • ¥100 求用matlab求解上述微分方程的程序代码
  • ¥15 MAC安装佳能LBP2900驱动的网盘提取码
  • ¥400 微信停车小程序谁懂的来
  • ¥15 ATAC测序到底用什么peak文件做Diffbind差异分析
  • ¥15 安装ubantu过程中第一个vfat 文件挂载失败