【发布时间】:2012-12-05 23:21:10
【问题描述】:
如何从外部 php 文件中使用 echo 函数在 javascript 中定义变量?
我们有 theconfigfile.php、thejsfile.js 和 thephpfile.php。
在 theconfigfile.php 我们有:
<?php
$path = 'http://example.com/home.php'; // Set your path
?>
在 thejsfile.js 我们有:
...
if (confirm("Are you sure you want to delete")) {
$.ajax({
type: "POST",
url: "http://example.com/home.php",
data: dataString,
cache: false
});
...
在 thephpfile.php 我们有:
<php
include "theconfigfile.php";
?>
<html>
<head>
<script type="text/javascript" src="thejsfile.js"></script>
</head>
<body>
...here is the code that uses file thejsfile.js...
</body>
</html>
我用了这个方法:
...
if (confirm("Are you sure you want to delete")) {
$.ajax({
type: "POST",
url: "<?php echo $path; ?>",
data: dataString,
cache: false
});
...
仅当 javascript 是代码的一部分时才有效。如果我在外部使用它,就像这样......
<script type="text/javascript" src="thejsfile.js"></script>
...不起作用!解决方案?
【问题讨论】:
-
为什么要通过 php 回显路径?为什么不直接在 javascript 中通过硬编码 url 或将路径分配到变量中以供以后使用?
-
使用 ajax 和内联 php 似乎是矛盾的,不是 IMO 最好的主意。
-
因为我有很多文件,我想从一个文件修改。
标签: php javascript html