WordPress wp_localize_script是做什么的? [英] what does WordPress wp_localize_script do?
问题描述
有人可以解释一下wp_localize_script()
的作用吗?
即使我已经在WP Codex中阅读了它,但我一开始也不了解它的作用.
can someone explain me what wp_localize_script()
do?
I don't understand what it does in the first place even I have read it in the WP Codex.
推荐答案
通过打印出JavaScript对象,您可以在客户端中使用PHP数据. 摘自法典:
It lets you use PHP data in the client by printing out a JavaScript object. From the Codex:
本地化脚本,但前提是已经添加了脚本. 可以 也可用于在页面中包含任意Javascript数据.
Localizes a script, but only if script has already been added. Can also be used to include arbitrary Javascript data in a page.
您这样使用:
// Register script as per Codex instructions.
// It doesn't have to contain anything but the file must exist
wp_register_script('handle', get_template_directory_uri() .'/js/dummy.js');
// Send data to client
wp_localize_script('handle', 'Data', array(
'url' => home_url(),
));
这将使用JavaScript打印对象:
This will print an object in JavaScript:
<script type='text/javascript'>
/* <![CDATA[ */
var Data = {"url":"http://..."};
/* ]]> */
</script>
现在在客户端中,您可以访问该数据:
Now in the client you can access that data:
console.log(Data.url);
构建插件时,这非常有用,因此您可以将客户端与服务器逻辑分开,而不必将JS和PHP都混合在同一个文件中.
It's very useful when you're building plugins so you can separate your client from your server logic instead of mixing JS and PHP all in the same file.
这篇关于WordPress wp_localize_script是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!