gpt4 book ai didi

php - 从php中的Ajax调用获取2个变量

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

我正在尝试从 php.ini 中的 ajax 获取 2 个变量。只要有一个变量,它就可以正常工作。 ajax 新手,所以我不确定如何包含第二个变量。截至目前,我得到的 msg_count 没有任何问题。我的ajax脚本如下:

function addmsg(type, msg) {

$('#msg_count').html(msg);

}

function waitForMsg() {

$.ajax({
type: "GET",
url: "notification/select.php",
async: true,
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();

});

select.php 脚本如下:

$sql = "SELECT * from notification where tousername='$tousername' and isread = 0";
$result = $con->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
echo $count;
$not=$row['notification'];
echo $not;

我能够正确地传递$count。我还需要将 $not 传递给 ajax。我将如何做到这一点?

我编辑的将其与 WHILE 循环一起使用的 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);

最佳答案

就像 @guradio 所说,在 ajax 属性中设置 dataType : 'json' 和要传递到 success block 的 json_encode 数据,如下代码所示:

$.ajax({
....
....
dataType : 'json', // added here
success : function ( data ) {
// access data from response
// access it using data.count, data.not
console.log(data)
// just called like original code
// passed on result `data`
addmsg( type, data );
// the rest of the code
}
...
});

function addmsg(type, msg){
// access it using msg.count, msg.not
console.log(msg.count)
$('#msg_count').html(msg);
}

Php 中:

$sql = "SELECT * from notification where tousername='$tousername' and isread = 0";
$result = $con->query($sql);
$row = $result->fetch_assoc();
$count = $result->num_rows;
$not=$row['notification'];
// added here
echo json_encode( array( 'count' => $count, 'not' => $not ) );

已编辑:这取决于您希望如何存储和填充数据

// defined container outside loop
$res = [];
while($row = mysqli_fetch_array($result)) {

$count = $result->num_rows;
$not=$row['notification_msg'];
array_push( $res, array( 'count' => $count, 'not' => $not ) );

}

echo json_encode($res);

建议(归功于 guradio):

必须注意的是,没有必要在ajax属性中添加async : true,因为Ajax的默认行为是异步的,默认值为TRUE除非你希望它是假的,但不推荐。

关于php - 从php中的Ajax调用获取2个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35217690/

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