php - 通过ajax请求动态刷新html页面中的php数据
问题描述
我有 2 个 div:一个是来自 php 变量的数据:
<div id="data"><?php echo "$strstr"?></div>
其次是ajax请求的div:
<div id="divButton">[CLICK ME]</div>
这是js代码:
$("#divButton").on("click", function() {
$.ajax({
type: "POST",
url: "test.php",
dataType: "json",
data: {simpledata:12345},
success : function(data) {
if (data.code == 200)
console.log("Success!");
else console.log("Error!");
}
});
最后是php代码:
<?php
$strstr = "A";
if ($_POST) {
$strstr = $strstr."A";
}
?>
如您所见,我需要通过单击第二个 div 来动态更新第一个 div。
我究竟做错了什么?
解决方案
HTML 代码应该是
<div id="data"><?php echo "$strstr"?></div>
<div id="divButton">[CLICK ME]</div>
Ajax 调用代码
$("#divButton").on("click", function() {
$.ajax({
type: "POST",
url: "test.php",
data: {simpledata:12345},
success : function(data) {
$("#data").html(data);
},
error : function() {
console.log("Error!");
}
});
test.php 代码应该是
<?php
$strstr = "A";
if ($_POST) {
$strstr = $strstr."A";
}
echo $strstr;
//It is advisable that do not close php tag
推荐阅读
- sql-server - Onprem DevOps 服务器 TFS2019 需要为用户配置文件创建报告。特别喜欢的电子邮件报告
- abp - Abp.io 的 Identity Server 可以从 URL 更改租户吗?
- c# - 无法在动态编译的代码中加载 System.ValueTuple
- php - 如何使用池建立 PHP PDO 连接
- azure - 如何使用服务托管标识在 Azure 中使用 Terraform 预配资源
- sql - 从列表中获取未在表列中定义的元素
- java - C# 客户端和 Java 服务器 - 文件上传获取错误数据。(有时)
- java - 插入数据库后preparedstatement停止工作
- java - 如何使用 Java 和 Selenium 运行电子应用程序
- react-native - Openstreetmaps 的 react-native-maps 中的暗模式