简体   繁体   English

将Javascript文件与View分开

[英]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) 我正在使用Codeigniter并希望将JavaScript与视图文件分开,但是许多JavaScript函数需要来自控制器的数据(取决于控制器的值)

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: 并且鉴于我有一个js函数:

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

How can I save this javascript snippets to some other file say posts.js ? 如何将该JavaScript代码段保存到其他文件,例如posts.js If I did something like this then I cannot use php variables inside the script. 如果我做了类似的事情,那么我将无法在脚本中使用php变量。

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 将JS文件另存为PHP文件,然后将值传递到该文件
  2. Declare all those variable in the view file globally 全局声明视图文件中的所有那些变量

you could pass the value as parameter to your js function, like post.js 您可以将值作为参数传递给js函数,例如post.js

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

view.php 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: 并使用以下ID通过js访问它们:

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

In this way you can use controller paramter in your js. 这样,您可以在js中使用控制器参数。

Help it will help you! 帮助它会帮助您!

the simplest method is that , define php variables as js variable in your view file 最简单的方法是,在视图文件中将php变量定义为js变量

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

then you can use that variable in your example.js file 那么您可以在example.js文件中使用该变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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