这是我的HTML代码。
<!DOCTYPE HTML>
<?php
$php_var = "Hello world from PHP";
?>
<html style="margin-top:-8px; margin-left:-8px;">
<head>
<meta charset="utf-8">
<title>Pure-Convert</title>
<script src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="calchome.css">
<script src="4func.js" type="text/javascript"></script>
<script src="converter.js" type="text/javascript"></script>
<script>
var js_var = <?php echo json_encode($php_var); ?>;
document.write(js_var);
</script>
</head>
<body >
<form action="cool.php" method="post">
<input name ="username" placeholder="Name">
<input name= "comment" placeholder="Make your mind heard..." />
<input type ="submit">
</form>
</body>
</html>
基本上我想要发生的是我想将$ php_var转换为javascript。这就是我的尝试。有人能帮助我做到这一点吗?
<script>
var js_var = <?php echo json_encode($php_var); ?>;
document.write(js_var);
</script>
答案 0 :(得分:0)
尝试
<script>
var js_var = "<?php echo $php_var; ?>";
document.write(js_var);
</script>
答案 1 :(得分:-1)
您不需要document.write(js_var);
。它的作用是将该值写入DOM / HTML,可能会弄乱所有内容(取决于值)。
<? php echo( '<script>var my_var=' . $my_value . ';</script>'); ?>
// In further js:
console.log( my_var );