简体   繁体   中英

Separate Javascript file from View

I am using Codeigniter and want to separate the JavaScript from the view files, but many of the JavaScript functions need data from controller (it depended on values from controllers)

ex:

controller :

function show_post() {
    $data['data'] = $this -> get_data();                 //some data
    $data['random_key'] = $this -> generate_random();    //returns a random value
    $this -> load -> view('posts', $data);
}

and in view I have a js function:

<script>
    function get_random() {
        return "<?= $random_key; ?>";
    }
</script>

How can I save this javascript snippets to some other file say posts.js ? If I did something like this then I cannot use php variables inside the script.

What is the best way to achieve this in terms of Performance and Maintenance?

Some other ways I do not want to follow :

  1. Save the JS file as a PHP file and then pass the values to that file
  2. Declare all those variable in the view file globally

you could pass the value as parameter to your js function, like post.js

function get_random( param ) {
    //use param here
}
//OR
function get_random( ) {
    //get arguments like
   var firstArg = arguments[0]; 
}

view.php

//include post.js file
//call the js function passing php variable as parameter, like
get_random("<?php echo $random_key; ?>");

did you mean something like this

One way to do it by using hidden fields, in your case store them in hidden field like:

<input type="hidden" value="<?php echo $random_key;?>" id="randomkey">

and access them in js by using ID like:

$("#randomkey").val();

In this way you can use controller paramter in your js.

Help it will help you!

the simplest method is that , define php variables as js variable in your view file

<script type="text/javascript">
    var random_key = <?= $random_key; ?>;
</script>

then you can use that variable in your example.js file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM