[英]How can I correctly print out data to a webpage using json_encode?
我在wepbage上有一个按钮,它将使用ajax
显示来自db的数据,因此不必刷新页面。 当我单击按钮并查看源代码并转到“网络”选项卡时,数据将正确显示,但实际上没有任何内容回显到页面。 这是我相关的getItem.php
。 这是我的php代码:
mysqli_select_db($con,"items");
$sql="SELECT * FROM items";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
$rows[] = array_map('utf8_encode', $row);
echo json_encode($rows);
//echo json_last_error();
和按钮click
jQuery函数:
$(document).ready(function () {
$('#button1').click(function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "getItem.php",
dataType: "html",
success: function (msg) {
if (msg.success) {
$("#responsecontainer").html(msg);
} else {
alert("error");
}
});
});
});
使用if语句,您正在检查msg.success
是否为true,但是您告诉ajax调用返回的dataType
应该为html形式,以便根据您提供的代码比较未定义的值,我认为您相当寻找是这样的。
$.ajax({
type: "GET",
url: "getItem.php",
dataType: "html",
success: function (msg) {
$("#responsecontainer").html(msg);
},
error: function () {
alert("error");
}
});
});
不过,如果您想对成功函数中的数据进行处理,则需要对其进行解析或将dataType: "html",
更改为dataType: "json",
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.