Cakephp: how to pass values into a javascript file?

天大地大妈咪最大 提交于 2021-02-19 04:19:17

问题


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

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

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.


回答1:


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>

Any javascript elsewhere should be able to use these variables.

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.




回答2:


Do you have some code that runs automatically? You could wrap it inside a function, and pass the function the necessary parameters.

For example, let's you currently have the following code in my-script.js:

window.onload = function() {
  alert('My favorite fruits are apples, and my favorite color is red.');
}

Wrap it in a function like this:

function initialize(args) {
  window.onload = function() {
    alert('My favorite fruits are ' + args.fruit +
     ', and my favorite color is ' + args.color + '.');
    }
  }

Then, output a <script> element using PHP somewhere after my-script.js is loaded, and call the function. Here's an example output:

<script>
  initialize({fruit: 'apples', color: 'red'});
</script>



回答3:


$this->Js->set('varname',$value);

from js file

var myvar = window.app.varname;



回答4:


These are following step:

1) Include the js helper in AppController.php

public $helpers = array('Js');

2) Now Declare js variable in ctp file Like that way :

$state = 'rajasthan';
$this->Js->set('state_name',$state);
echo $this->Js->writeBuffer(array('onDomReady' => false));

3) Now Use this js vairable "state_name" in js file Like that way :

console.log(window.app.state_name);
var state = window.app.state_name;


来源:https://stackoverflow.com/questions/5061291/cakephp-how-to-pass-values-into-a-javascript-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!