简体   繁体   English

当我为PHP变量赋值时可以调用JavaScript函数吗?

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

As soon as I assign a value to my PHP variable $msg ... 一旦给我的PHP变量$msg了一个值...

$msg = 'Some message'; 

... I want to call a JS function like this : ...我想这样调用JS函数:

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

Is it possible ? 可能吗 ?

If I understand you correctly, this will be the answer for your question. 如果我理解正确,这将是您的问题的答案。

$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>'; 
}

From what I understood, I think you would like to display a JS alert box when a desirable value is assigned to $msg . 据我了解,我认为您希望在$msg分配了一个理想值时显示一个JS警告框。 The following code may help. 以下代码可能会有所帮助。

<?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*/
}
?>

The basic structure remains the same even if the value of $msg is not hardcoded in your case. 即使$msg的值未根据您的情况进行硬编码,其基本结构也保持不变。 Only the condition in if may vary depending on the variable type. if的条件可能会根据变量类型而有所不同。

You could also use if($msg) . 您也可以使用if($msg) This simply checks if $msg has been assigned a value or not. 这只是检查$msg是否已分配值。

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

Maybe something in DOM like this, to keep php and javascript separate: 也许这样的东西在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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM