Passing dynamic data in javascript

A good idea is not to hardcode everything that can change in javascript. For example, I want to have the url generated by php.

I can write

echo "
<script ...>
    var anUrl = $urlFromPHP;
</script>";

and then:

<script ...>
    // some code
    $.ajax({ url: anUrl ... });
</script>";

Is there a better way to do this? Does anyone know if there is any built-in mechanism in the yii structure?

+3
source share
2 answers

I personally like the conversion between php variables (arrays, ...) into a javascript json_encode object . For example, it is convenient for complex arrays.

<?php 
// From manual:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);
?>
// results
{"a":1,"b":2,"c":3,"d":4,"e":5}
+1
source

This is a great way to do it. Although you probably need quotes around the javascript url string:

var anUrl = '$urlFromPHP';
0

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


All Articles