Output JS statement in PHP and solution of garbled code problem
- 2021-11-24 01:09:53
- OfStack
How to output js statement in php?
Example
<?php
$classState="";
if($state==0){
$classState=" Class has been dismissed ";
}
else{
$classState=" Is in class ";
}
echo "<script type='text/javascript'>
function getState(){
var cs = ".$state.";
return cs;
}
</script>";
?>
Elsewhere on the page, you can refer directly to the js method output from php.
Garbled code problem when using echo js code on php page
When using php as a control script for the front page of html, it is often necessary to display something in the foreground. For example, use echo output. Recently, there is such a requirement on the project, and I used it
echo "<script></script>"
Such code, debug completely normal in the local, but 1 deployed to the server, js output to the foreground on the display of garbled code. Looking for 1 from the Internet, some people say that it can be set
<script type="charset:utf-8;"></script>
But after this setting, it is found that the problem still exists. Analysis, the reason why garbled code exists is that the page code is not 1 with the browser display code, or that the front-end html page is not 1 with the background control page code. So, first set the php encoding, use the header function,
header("Content-type:text/html;charset:utf-8")
. Then refresh the browser and display it normally. Description should be php code and browser parsing page code is not 1.
Summarize