![](/img/trans.png)
[英]How to use variable in variable to define php function and later echo it
[英]How to define a variable in JavaScript with PHP echo function?
如何在外部php文件中使用echo函數在javascript中定義變量?
我們有theconfigfile.php,thejsfile.js和thephpfile.php。
在configfile.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>
......不起作用! 解決方案?
有幾種方法可以做到這一點。
您可以將您的Web服務器配置為使用PHP處理擴展名為.js
文件,並在那里注入您的PHP。 當然,這意味着你需要一種方法來實際計算你的變量,這會減慢你提供常規javascript內容的速度。
您可以簡單地將PHP變量輸出到像這樣的<script>
元素中的Javascript變量
<script type="text/javascript">
var path = "<?php echo $path; ?>";
</script>
然后在AJAX中訪問此path
變量。 大多數人可能會使用第二種方法。
您可以將thejsfile.js
重命名為thejsfile.php
,將以下內容添加到它的開頭 ,並且應該為PHP解析它:
<?php header("Content-type: text/javascript"); ?>
然后像這樣引用它:
<head>
<script type="text/javascript" src="thejsfile.php"></script>
</head>
您的另一個選擇是將服務器設置為解析PHP的.js
文件。
在thephpfile.php中,
<html>
<head>
<script type="text/javascript">
var config = { url: '<?= $path; ?>' };
</script>
<script type="text/javascript" src="thejsfile.js"></script>
</head>
然后你可以在你的javascript中使用config.url訪問它。
您只能以這種方式將值放入PHP處理的文件中。
外部JavaScript文件不由PHP處理,因此它們按原樣鏈接而沒有替代。
除非您通過JSONP向另一台服務器發帖,否則您可能只考慮在Javascript中使用硬編碼的相對路徑,這樣您就不需要將路徑從服務器發送到客戶端:
...
$.ajax({
type: "POST",
url: "home.php",
data: dataString,
cache: false
});
....
但是,如果這是一個經常更改的URL並且它確實需要可配置,那么您可以將PHP變量作為腳本回顯出來,就像這樣“
<html>
...
<script src="thejsfile.js" type="text/javascript">
<script type="text/javascript">
// 'path' is a variable that is defined in thejsfile.js
path = '<?php echo htmlentities($path) ?>';
</script>
...
每當您從服務器向客戶端輸出信息時(特別是作為Javascript),您必須非常小心它被轉義以防止腳本攻擊(即允許人們將JavaScript注入您的代碼)。 在這種情況下,沒有理由允許任何類型的HTML字符。
使用外部JS文件時您可以將值存儲在隱藏字段中,並使用JavaScript檢索字段值。
<input type="hidden" name="path" id="path" value="<?php echo $path; ?>" />
並在javascript(我將使用jquery)
var path = $('#path').attr('value');
顯然,您可以將變量寫入頁面上的腳本標記,但如果使用任何高級類型的模式,則可能很難訪問該變量。
echo "<script type='text/javascript'>var AccomodationInfoForm4 =".$path."</script>";
只需嘗試回應上面顯示的方式,您就可以隨意訪問您的變量。因為這將全局提供給您頁面上的所有js
文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.