Javascript 如何在js文件中编写php代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3879010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write the php code in js file
提问by Meena
Is my program i divide the pages as a div in the first div i added this code
我的程序是我在第一个 div 中将页面划分为 div 我添加了此代码
<?php
$table="am_users";
$query="select distinct(`user_email`) from $table";
$result=mysql_query($query);
$num_rows = mysql_num_rows($result);
while($data1=mysql_fetch_array($result))
{
$data[]=$data1['user_email'];
}
sort($data);
foreach($data as $search_term)
{
$js_data[] ="\"" . $search_term . "\"";
}
<script type="text/javascript">
var collection = [<?php echo implode($js_data, ","); ?>];
</script>
?>
below this i include my css file but division 1 is working in division 2 the css is not applied . This Problem is due to the div 1 had Js variable value If I remove the var collection = []; statement then the css working fine . So Is It possible to pass the value from PHP file to JS file On Loading Time
在此之下,我包含了我的 css 文件,但第 1 部分在第 2 部分工作,未应用 css。这个问题是由于 div 1 有 Js 变量值如果我删除 var collection = []; 声明然后 css 工作正常。那么是否可以在加载时将值从 PHP 文件传递到 JS 文件
回答by Joyce Babu
Save the file as .php instead of .js and add
将文件另存为 .php 而不是 .js 并添加
Header("content-type: application/javascript");
. at the beginning of the file. After that you will be able to link to the file as
. 在文件的开头。之后,您将能够链接到该文件
<script type="text/javascript" src="youfile.php"></script>
回答by Haim Evgi
what you need is to call to file with php extension
你需要的是调用带有 php 扩展名的文件
like
喜欢
<script type="text/javascript" src="/includes/slideshow.js.php"></script>
and in the beginning of php file
并在 php 文件的开头
Header("content-type: application/x-javascript");
look the example in http://www.givegoodweb.com/post/71/javascript-php
回答by Mahavir
Save the file named abc.js
to abc.js.php
, hence server will come to know that it contains some phpquestion, so that it will process first phpcontent then replace the result in .js
file and send to browser, By doing this the .js
file will contain dynamic contents..
保存名为abc.js
to的文件abc.js.php
,因此服务器会知道它包含一些php问题,因此它将首先处理php内容,然后将结果替换为.js
文件并发送到浏览器,通过这样做,.js
文件将包含动态内容..
回答by Rahul Patwa
In the questions code i see that the value of a JS var is being set from PHP using echo. What I need to do is the other way around. That is store values of JS vars into PHP var properties. Is it possible ? I am able to include the JS file as PHP, but not able to pass the value from JS to PHP var. PS - the values from JS come from a AJAX call, so I need to update the values regularly into PHP var..
在问题代码中,我看到正在使用 echo 从 PHP 设置 JS var 的值。我需要做的是反过来。那就是将 JS 变量的值存储到 PHP 变量属性中。是否可以 ?我可以将 JS 文件包含为 PHP,但无法将值从 JS 传递到 PHP var。PS - 来自 JS 的值来自 AJAX 调用,所以我需要定期将值更新到 PHP var..