使用wp_localize_script无法正确传递数据 [英] Data not passing correctly with wp_localize_script

查看:152
本文介绍了使用wp_localize_script无法正确传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将PHP数据传递给JS脚本。
我正在使用wp_localize_script函数。

I'm trying to pass PHP data to a JS script. I'm using the wp_localize_script function.

wp_register_script('googlechart', 'https://www.gstatic.com/charts/loader.js');
wp_register_script('mygaloochart_script', plugins_url('chart.js', __FILE__), array('googlechart'));

//I'm not using $atts directly for reasons
$dataToBePassed = array (
        'chart' => $atts['chart'],
        'element' => $atts['element'],
        'elementtype' => $atts['elementtype'],
        'title' => $atts['title']
);

wp_localize_script('mygaloochart_script', 'php_vars', $datatoBePassed);

wp_enqueue_script('googlechart');
wp_enqueue_script('mygaloochart_script');

这是JS脚本的第一行 mygaloochart_script

This is the first line of the JS script mygaloochart_script:

console.log(php_vars.chart);

但是,我在控制台中收到以下错误:

However, I get the following error in the console:

TypeError: php_vars is null

什么是我做错了吗?

推荐答案

你的数组名称是 $ dataToBePassed 。但是,您在 wp_localize_script 函数中传递 $ datatoBePassed 。大T,小T。 PHP 变量名称区分大小写

The name of your array is $dataToBePassed. However you are passing $datatoBePassed in your wp_localize_script function. Big T, small t. PHP variable names are case sensitive.

这篇关于使用wp_localize_script无法正确传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆