首页 > 解决方案 > 通过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。
我究竟做错了什么?

标签: phpjqueryhtmlajaxpost

解决方案


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 

推荐阅读