简体   繁体   English

如何将PHP值传递到外部JavaScript文件

[英]How to pass PHP value to external JavaScript file

I am trying to pass my variables from my main page to external JS file. 我试图将我的变量从我的主页传递到外部JS文件。 Please see my code. 请看我的代码。

Main page: 主页:

<script type="text/javaScript">
$(document).ready(function(){

var add_project_link="<?= base_url().'add_project/show_form'; ?>";
var add_agent_link="<?= base_url().'agent/add_agent';?>";
});

</script>

External JS 外部JS

 $(document).ready(function(){
    alert(add_project_link);
    alert(add_agent_link);
  });

I got: 我有:

uncaught referenceError add_project_link is not defined. 未定义的没有引用错误error add_project_link。

I thought the external JS would catch the variable declared in main page. 我以为外部JS会捕获在主页中声明的变量。 Any thoughts? 有什么想法吗? Thanks a lot! 非常感谢!

Before you call your external JavaScript file, define your variables using PHP: 调用外部JavaScript文件之前,请使用PHP定义变量:

<script type="text/javascript">
   var site_url = '<?php echo site_url(); ?>';
   var current_url = '<?php echo current_url(); ?>';
</script>
<script type="text/javascript" src="file.js"></script>

In your external file.js you can now use site_url as a variable. 现在,您可以在外部site_url中使用site_url作为变量。

Take your php generated variables out of document ready. 将您的php生成的变量移出文档准备就绪。 They are not accessible anyhwere else in your code due to closure of the ready event function they are in 由于关闭了它们中的ready事件函数,因此在您的代码中其他任何地方都无法访问它们

What I would do is to store those variables to something easily called by JS later. 我要做的是将这些变量存储到稍后由JS轻松调用的东西中。

<input type="hidden" id="hidden_var" value="<?= base_url().'add_project/show_form'; ?>" />

var add_project_link = $('#hidden_var').val();

You just write in the head tag 你只要写在head标签上

<script type="text/javaScript">    
var add_project_link="<?= base_url().'add_project/show_form'; ?>";
var add_agent_link="<?= base_url().'agent/add_agent';?>";
</script>

Then load your External JS after the script above 然后在上面的脚本之后加载您的外部JS

best way is to to store those path in some tags like 最好的方法是将这些路径存储在某些标签中,例如

<span id="site_url" style="display:none;"><?php echo site_url(); ?></span>
<span id="current_url" style="display:none;"><?php echo current_url(); ?></span>

then you can access this this using jquery like 然后您可以使用jquery这样访问此

$('#site_url').html();
$('#current_url').html()

the simplest thing to do is to bring the script into a script tag on the php page 最简单的方法是将脚本带入php页面上的script标签

you can go down the URL string variable route, but it's unnecessary I think 您可以使用URL字符串变量路由,但是我认为这是不必要的

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

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