簡體   English   中英

在Javascript中傳遞PHP變量

[英]Passing PHP variable in Javascript

我試圖用Javascript傳遞PHP變量,但它不起作用。 請在下面找到我正在使用的代碼:

function delete_id(id)
{
     if(confirm('Are you sure you want to permanently delete this record?'))
     {
        window.location.href='index.php?cabinet_id_delete='+id+'&estimate_id=<?php echo $estimate_id; ?>';
     }
}

也許我需要編輯調用JS的代碼? 在下面:

<a href='javascript:delete_id(".$rows['estimates_cabinet_id'].")'>DELETE</a>

誰能看到我需要做些什么才能使它工作?

謝謝,

約翰

您將無法使用JavaScript文件中的php。 將變量“傳遞”到javascript的一些常用方法可能是將其打印到html頁面中:

index.html

<script>
  var estimate_id = <?php echo $estimate_id; ?>;
</script> 

main.js

esitmate_id現在可以用作全局變量。

function delete_id(id)
{
  if(confirm('Are you sure you want to permanently delete this record?'))
  {
    window.location.href='index.php?cabinet_id_delete='+id+'&estimate_id='+estimate_id;
  }
}

或者,您可以只在腳本標簽的index.php文件中使用當前代碼

根據您的評論,看來您有一個有效的php腳本,在其中您鏈接到js文件(通過<script src=...> )。

此類js文件中的php不會作為php執行,而只是直接發送給瀏覽器。

因此,簡單的解決方案是將js代碼移動到您的php文件中,在其中輸出html:

<?php
$estimate_id=1;
?>
<html>
<script>
function delete_id(id)
{
    if(confirm('Are you sure you want to permanently delete this record?'))
    {
       window.location.href='index.php?cabinet_id_delete='+id+'&estimate_id=<?php echo $estimate_id; ?>';
    }
}
</script>
<?php
// more php...
?>

另一個解決方案可能是使您的服務器將js文件作為php執行。
這可能很棘手(您不能簡單地傳遞參數,您會有更高的安全風險),但可以使用-我不建議這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM