这是我的代码:
<script>
var a="ABC";
</script>
<?php
$Y="<script>document.write(a)</script>";
$A=mysqli_connect("127.0.0.1", "root", "root");//连接mysql服务器
mysqli_select_db($A, "ax");//连接数据库
mysqli_query($A, "set name utf8");//执行语句:设置中文编码
$A6="insert into ax01
(用户,正文)
values
('B','$Y')
";
mysqli_query($A,$A6);//执行语句:添加数据
我希望数据库中存入的数据是“ABC”,然而数据库中存入的数据是:
(前12行不用看。13到17行是上面这段代码五次运行的结果)
我不知道哪里出错了。
我试过这样的代码:
<script>
var a="ABC";
</script>
<?php
$Y="<script>document.write(a)</script>";
echo $Y;
这个代码是能正常运行的。
也试过这样的代码:
<?php
$Y="ABC";
$A=mysqli_connect("127.0.0.1", "root", "root");//连接mysql服务器
mysqli_select_db($A, "ax");//连接数据库
mysqli_query($A, "set name utf8");//执行语句:设置中文编码
$A6="insert into ax01
(用户,正文)
values
('B','$Y')
";
mysqli_query($A,$A6);//执行语句:添加数据
这个代码也是能正常运行的。
我不知道为什么二者结合就出错了。
服务器端无法直接调用客户端js变量,需要用ajax提交后获取~帮助到你请点个采纳【右上角】,谢谢
<script>
var a = "ABC";
$.ajax({
url: 'xxx.php',///修改这里php的路径
data: { a: a },
type:'POST',
complete: function (xhr) {
alert(xhr.responseText)
}
})
</script>
然后php获取ajax提交的数据就没问题了
<?php
$Y=$_POST["a"];
$A=mysqli_connect("127.0.0.1", "root", "root");//连接mysql服务器
mysqli_select_db($A, "ax");//连接数据库
mysqli_query($A, "set name utf8");//执行语句:设置中文编码
$A6="insert into ax01
(用户,正文)
values
('B','$Y')
";
mysqli_query($A,$A6);//执行语句:添加数据
echo "插入成功";
?>
为何要把前端的参数直接写入,可以用接口的方式,把你这个参数传给后端API