简体   繁体   中英

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. When I look at the js file in my editor it shows errors every time there is php code. 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).

  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()): ?> . I also add and update mysql table based on different events eg clicking a button.

  3. Everything works fine if I have code directly in tags in index.php file.

  4. When I remove php from js file then the external file works (no surprise there) both in .js and .php forms.

Thanks

What you want to do, is have js files without any php code in them.

Then in php, create a javascript as follow :

<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.)

in env.current_user you'll have all your user informations.

Note that you may want to filter that because in this example, any aknowledged user could access its information on client side.

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