开发者

Javascript in PHP code

开发者 https://www.devze.com 2022-12-27 17:09 出处:网络
I found this code on the internet on how to to display message/pop up box. <? echo \"<script language=\\\"JavaScript\\\">\\n\";

I found this code on the internet on how to to display message/pop up box.

<? echo "<script language=\"JavaScript\">\n"; 
   echo "alert('$msg1')";
   echo "alert('$msg2')"; 
   </script>"; 
?>

AND

<? echo "<script>alert('$msg1' )</script>" <?

I want to display messages to the user by popup message. all the messages will be appears in one message box. For above example, the message will be appeared in two box.

Can it be done in all in one box? I try using '\n' or 'br>'...also cannot or i did it wrong? Any idea? Is there any refer开发者_JAVA技巧ence or tutorial on this?


<?
   echo "<script type=\"text/javascript\">\n"; 
   echo "alert('$msg1" . '\n' . "$msg2');";
   echo "</script>"; 
?>

EDIT: But your users may find alert annoying. Look into DIV-based dialogs.

"alert('$msg1" and "$msg2');" use double quotes to allow for variable interpolation. '\n' is single-quoted so backslash will not be an escape (we want it to be interpreted by JS, not PHP). . is PHP's concatenation operator.


There's a few other issues here.

  • It is using Javascript alert boxes, which are ugly, and modal. It's bad for users. Modal in the whole-of-browser sense, so (depending on the browser) users can't even go and do something in another tab while this message is on screen; they must dismiss it first. It's much better to place the message in a well styled <div> for example. You could still use some unobtrusive script (like jQuery) to allow users to hide the box if you were so inclined.

  • Any apostrophes in $msg1 and $msg2 won't be escaped in the Javascript output. This can be a security problem if you're accepting user input as part of these variables. You could use addslashes() to partially fix this, but you'd also need to escape the characters "</" (or "</script" if using HTML) if they might appear, and possibly other variants too.

If you read and accept the above problems and still want to achieve this, here's a safer (though I'm still not sure if it's perfectly safe) alternative:

<?
echo "<script type=\"text/javascript\">"; 
echo "alert('" . str_replace("</", "<'+'/", addslashes($msg1).'\n'.addslashes($msg2)) . "');";
echo "</script>"; 
?>


Instead of:

   echo "alert('$msg1')";
   echo "alert('$msg2')"; 

Try:

   echo "alert('$msg1, $msg2')";


Here is modified example from w3schools.com tutorial if you want to display messages before submit is processed:

<html>
   <head>
      <script type="text/javascript">
         function disp_alert()
         {
           <?php echo "alert('".$msg1.'\n'.$msg2."');"; ?>
         }
      </script>
   </head>
   <body>  
      <input type="button" onclick="disp_alert()" value="Display alert box" />    
   </body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号