简体   繁体   English

外部JavaScript文件中的PHP导致其无法加载

[英]PHP in external javascript file causing it to not load

Exactly what the title says. 标题确切地说。 I originally had a lot of javascript in my index.php file and when I attempted to put it in an external js file and load it like I did with other js files, the file did not load. 我最初在index.php文件中有很多javascript,当我尝试将其放在外部js文件中并像对待其他js文件那样加载它时,该文件未加载。 When I look at the js file in my editor it shows errors every time there is php code. 当我在编辑器中查看js文件时,每次有php代码时都会显示错误。 How do I work around this issue? 如何解决此问题?

  1. I have tried renaming it as a php file and that didn't work (I get errors everywhere). 我尝试将其重命名为php文件,但没有用(我到处都有错误)。

  2. The reason I have php code in there is because there are a lot of "if" statements that check different things about signed in user eg <?php if (Auth::instance()->current_user()): ?> . 我里面有php代码的原因是因为有很多“ if”语句检查有关登录用户的不同内容,例如<?php if (Auth::instance()->current_user()): ?> I also add and update mysql table based on different events eg clicking a button. 我还基于不同事件(例如单击按钮)添加和更新mysql表。

  3. Everything works fine if I have code directly in tags in index.php file. 如果我直接在index.php文件的标记中包含代码,则一切正常。

  4. When I remove php from js file then the external file works (no surprise there) both in .js and .php forms. 当我从js文件中删除php时,外部文件就会以.js和.php格式工作(毫无意外)。

Thanks 谢谢

What you want to do, is have js files without any php code in them. 您要执行的操作是将js文件中没有任何php代码。

Then in php, create a javascript as follow : 然后在php中,创建如下javascript:

<html>

<head>
<script>
var env = {'current_user':JSON.parse(<?=json_encode(Auth::instance()->current_user())?>), 'foo':'bar'}
console.log(env); //remove this before deploying in production
</script>
</script type='text/javascript' src='yourscript.js'></script>
<!--  other scripts here -->
</head>
...

Now you can use the global env variable in all your scripts to access your user informations (check console for details : F12 - console tab, then reload.) 现在,您可以在所有脚本中使用全局env变量来访问用户信息(检查控制台以获取详细信息:F12-控制台选项卡,然后重新加载。)

in env.current_user you'll have all your user informations. env.current_user您将拥有所有用户信息。

Note that you may want to filter that because in this example, any aknowledged user could access its information on client side. 请注意,您可能需要过滤,因为在此示例中,任何公认的用户都可以在客户端访问其信息。

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

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