当我为 PHP 变量赋值时,是否可以调用 JavaScript 函数


Is It possible to call a JavaScript function when I assign a value to a PHP variable?

一旦我为我的 PHP 变量分配一个值$msg......

$msg = 'Some message'; 

。我想像这样调用一个JS函数:

function showSuccess() { 
    alert('success')
}

可能吗?

如果我理解正确,这将是您问题的答案。

$msg = 'some value your are going to assign';
if($msg) //checking $msg variable has some value or not
{
   print '<script type="text/javascript">showSuccess()</script>'; 
   /* or */
   print '<script type="text/javascript">alert("succeess")</script>'; 
}

据我了解,我认为您希望在将所需值分配给$msg时显示 JS 警报框。以下代码可能会有所帮助。

<?php
$msg="Hello";  
  /*this is just to give you an idea 
  and so I am considering value of 
  $msg as hardcoded*/
if($msg!="")
/*may vary with the variable type,for
example if($msg!=0) in case of int*/
{
echo "<script>alert('successfull');</script>"
  /*echo adds stuff to the html
  document on the go*/
  /*the above JS code will be added to
  the HTML document and executed
  to display an alert box*/
}
?>

基本结构保持不变,即使您的情况下没有硬编码$msg的值也是如此。只有if中的条件可能因变量类型而异。

您也可以使用 if($msg) .这只是检查是否已$msg分配值。

 if($msg!)
 //universal-checks if value is assigned
 {
 echo "<script>alert('successfull');</script>"
 }
也许在

DOM 中是这样的东西,以保持 php 和 javascript 分开:

<?php
    //assign your value   
    $value = true;
?>
<input id="value" type="hidden" value="<?php if ($value) { echo 'true'; } ?>" />
   <script>
       var value = document.getElementById('value').value;
       if (value) {
          alert(value);
        }
    </script>