Cakephp:如何将值传递到javascript文件? [英] Cakephp: how to pass values into a javascript file?

查看:48
本文介绍了Cakephp:如何将值传递到javascript文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图中包含一些javascript,并且在此线程中使用了inkedmn的方法: adding-page-specific-javascript-to-each-view-in-cakephp

I have some javascript that is being included in a view and I used inkedmn's method in this thread: adding-page-specific-javascript-to-each-view-in-cakephp

所以我现在在视图中有以下代码:

So I now have the following code in my view:

$this->set('jsIncludes',array('google'));   // this will link to /js/google.js

但是我需要将视图中的一些值传递到javascript文件中,我不确定如何完成此操作.

But I need to pass some values from the view into the javascript file and I'm unsure of how to accomplish this.

更新:我猜一个选择是回显php文件中的值,将其括在div标签中,然后在javascript代码中使用getElementById().

Update: I guess one option would be to echo the values in the php file, enclose in a div tag, and then use a getElementById() in the javascript code.

推荐答案

您应该能够插入< script>使用所需的数据将其直接标记到HTML中:

You should be able to inject a <script> tag directly into the HTML with the data you want:

<script type="text/javascript">
var mynum = <?php echo intval($num); ?>;
var mystring = "<?php echo addslashes($string); ?>";
var myarray = <?php echo json_encode(array("one" => 1, "two" => 2)); ?>;
</script>

任何其他地方的javascript都应该能够使用这些变量.

Any javascript elsewhere should be able to use these variables.

注意:如果使用此数据的代码在页面中的较早位置运行,则他们显然将看不到这些变量.如果是这样,请使用setTimeout()或document.onready事件,确保首先加载数据,或者可以延迟代码运行直到页面完全加载.

Note: if the code using this data runs earlier in the page, they obviously won't see these variables yet. If that's the case, either ensure that your data is loaded first, or you can delay the code from running until the page is fully loaded, using either setTimeout() or a document.onready event.

这篇关于Cakephp:如何将值传递到javascript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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