一旦我给我的PHP变量$msg赋值...
$msg = 'Some message'; ..。我想像这样调用一个JS函数:
function showSuccess() {
alert('success')
}有可能吗?
发布于 2016-02-13 03:52:52
如果我没理解错的话,这就是你问题的答案。
$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>';
}发布于 2016-02-13 03:54:14
据我所知,我认为当一个所需的值被分配给$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>"
}发布于 2016-02-13 05:06:08
也许在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>https://stackoverflow.com/questions/35370958
复制相似问题