php - 最佳实践 : Including PHP in your JavaScript code

标签 php javascript jquery

我是一名 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/

相关文章:

javascript - 我想在我的 div 标签中加载 html 页面

php - 如何将结果 SQL 不同查询设置为一个或不同的变量?

php - 数据库关系

php - Laravel Eloquent 查询哪里喜欢关系?

php - 用户在注册/认证之前将商品添加到购物车

javascript - .includes() 检查 prompt() 中的关键字

javascript - 如何使用 TypeScript 的 keyof 访问器定义返回类型?

javascript - 如何从模型获取 ODATA 值并将其显示在消息框中

javascript: string.replace 不起作用

javascript - 如何在其中保留 div 的文本,如果更大,则 div 向下扩展?