gpt4 book ai didi

php - Ajax 和 PHP 存在 while 循环问题

转载 作者:行者123 更新时间:2023-12-01 07:47:12 26 4
gpt4 key购买 nike

我有一个ajax需要返回一些值,但是如果我使用while()从我的数据库获取所有结果,则返回“无”。我哪里出错了?

我的 Ajax 脚本发布如下:

<script type="text/javascript" charset="utf-8">
function addmsg(type, msg) {
var obj = jQuery.parseJSON(msg);
// Your count variable
var count = obj.count;
// Your not variable
var not = obj.not;
$('#msg_count').html(count);
$('#notification').html(not);

}

function waitForMsg() {
$.ajax({
type: "GET",
url: "notification/select.php",
cache: false,
timeout: 50000,

success: function(data) {
addmsg("new", data);
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
};

$(document).ready(function() {

waitForMsg();

});
</script>

我的 php 脚本发布如下:

 $result = mysqli_query($con, "SELECT * from notification where tousername='$tousername' and isread = 0");

while ($row = mysqli_fetch_array($result)) {
$count = $result - > num_rows;
$not = $row['notification_msg'];
$res = [];
$res['count'] = $count;
$res['not'] = $not;
}
echo json_encode($res);

最佳答案

您正在循环中覆盖结果变量:

while (...) {
...
$res=[];
...
}

你可能想要这样的东西:

$res['count'] = $result->num_rows;
while($row = mysqli_fetch_array($result)) {
$res[]['not'] = $row['notification_msg'];
}
echo json_encode($res);

关于php - Ajax 和 PHP 存在 while 循环问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35219215/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com