简体   繁体   English

从php文件中定义js文件中的变量

[英]Defining a variable in a js file, from a php file

I have a javascript file that needs a value from a variable in a php script in which the JS file is being called. 我有一个javascript文件需要来自php脚本中的变量的值,其中正在调用JS文件。

<?
$sid = session_id();
?>
<html>
<head>
<script src="javascript.js" type="text/javascript"></script>
...

How can i get $sid into the js file for use? 如何将$ sid放入js文件中以供使用?

<html>
<head>
<script src="javascript.js" type="text/javascript"></script>
<script type="text/javascript">
    var myFile = 'myfile.php?sid=' + "<?php echo session_id() ?>";        
    $('#stuff').fadeOut("fast").load(myFile).fadeIn("fast");
</script>

The order of inclusion somewhat depends on what is inside javascript.js. 包含的顺序在某种程度上取决于javascript.js中的内容。 If you are using the declared 'myFile' variable inside, declare it first. 如果你在里面使用声明的'myFile'变量,先声明它。 If it's just a lib, eg jQuery, declare it afterwards. 如果它只是一个lib,例如jQuery,则在之后声明它。

Why on earth do you pass SID explicity? 为什么你传递SID表达? It should be passed throught cookies by PHP. 它应该通过PHP传递给cookie。 Any other variable could be passed through sessions. 任何其他变量都可以通过会话传递。

$('#stuff').fadeOut("fast").load('myfile.php?sid=<?php echo session_id() ?>').fadeIn("fast");

Read more about client/server languages and differences between them. 阅读有关客户端/服务器语言及其之间差异的更多信息

<?
$sid = session_id();
?>
<html>
<head>
<script type="text/javascript">
var sid = '<?= $sid ?>';
</script>
<script src="javascript.js" type="text/javascript"></script>

Now you can use the sid variable in javascript.js, or any other JS code you load AFTER this. 现在您可以在javascript.js中使用sid变量,或者在此之后加载任何其他JS代码。

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

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