Cakephp: how to pass values ​​to javascript file?

I have javascript that is included in the view and I used the ink method in this thread: adding-page-specific-javascript-to-each-view-in-cakephp

So now I have the following code:

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

But I need to pass some values ​​from the view to a javascript file, and I'm not sure how to do this.

Update: I suggest that one option would be to echo the values ​​in the php file, wrap it in a div tag, and then use getElementById () in javascript code.

+3
source share
4 answers

You should be able to enter the <script> tag directly in the HTML with the required data:

<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 .

:, , , , . , , , , setTimeout(), document.onready.

+9

, ? .

, my-script.js:

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

​​:

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

<script>, PHP - my-script.js, . :

<script>
  initialize({fruit: 'apples', color: 'red'});
</script>
+1
$this->Js->set('varname',$value);

js

var myvar = window.app.varname;
0

This is the next step:

1) Enable js helper in AppController.php

public $helpers = array('Js');

2) Now declare the js variable in the ctp file this 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 the js file this way:

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

Source: https://habr.com/ru/post/1793486/


All Articles