我是一名 PHP phr34k 爱好者,沉迷于 JavaScript 来寻求一些知识。如果要在脚本中包含 php 代码,最好的方法是什么?我提供了一些示例代码作为我如何在脚本中包含 PHP 的示例。
这是一个有效的方法吗?
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP with JavaScript?</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="test.js.php"></script>
</head>
<body>
</body>
</html>
test.js.php
<?php
$foo = 'bar';
?>
$(document).ready(function() {
var foo = '<?php echo $foo; ?>';
alert(foo);
});
再次感谢!
最佳答案
同时在 test.js.php 中设置内容类型 header
header('Content-Type: text/javascript');
您还可以像这样内联定义foo
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP with JavaScript?</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
var foo = '<?php echo $foo;?>';
</script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
</body>
</html>
test.js
$(function(){
alert(foo);
});
关于php - 最佳实践 : Including PHP in your JavaScript code,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4865815/