我试图从php中的ajax获取2个变量。有一个变量,它的工作正常。 ajax的新手,所以我不确定如何包含第二个变量。截至目前,我正在获取msg_count,没有任何问题。我的ajax脚本如下:
struct node
{
int data;
}tree[100050];
/*
some codes
*/
int main()
{
int tot;
scanf("%d",&tot);
int tmp;
for(int i=0;i<=tot;++i){
scanf("%d",&tmp);
tree[i].data=tmp;
insert(i,1);
tmp=0;
}
}
select.php脚本如下:
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();
});
我能够正确传递$ count。我需要将$也传递给ajax。我该怎么做?
我编辑的PHP脚本与WHILE循环一起使用如下:
$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;
答案 0 :(得分:3)
就像@guradio说的那样,在ajax属性和dataType : 'json'
数据中设置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
,除非你想要它是假的,但不推荐。