我正在尝试从php函数读取响应,但响应是未定义的值。但是,如果我使用chromes inspect元素并进入网络选项卡,我可以读取项目的正确值。
这里是代码:
Javascript功能
function chatHeartbeat(){
$.ajax({
url: 'chat.php?action=chatheartbeat',
type: 'post',
dataType: 'json',
success: function(response) {
$.each(response.items, function(item){
//alert(item.m);
$(".chatboxcontent").append('<div class=chatboxmessage><span class="chatboxmessagefrom">'+item.f+': </span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
});
setTimeout('chatHeartbeat();',3000);
},
error: function(){
$(".chatboxcontent").append('<div class=chatboxmessage><span class="chatboxmessagefrom">ERROR!</span><span class="chatboxmessagecontent">UNKNOWN</span></div>');
alert("failed");
}
});
}
这里是php代码:
function chatHeartbeat() {
if ($idchat!=""){
$sql = "select * from chat where idchat=".$idchat." and recd=0 order by id ASC";
$result=$mysqli->query($sql);
if ($result->num_rows>0){
while($row=$result->fetch_array()){
$sqlup="UPDATE chat SET recd = '1' WHERE idchat = ".$row['id'];
if ($mysqli->query($sqlup)=== FALSE){
echo "Error updating record" . $mysqli->error;
}
$item.=<<<EOD
{
"f": "{$row['from']}",
"m": "{$row['message']}"
},
EOD;
}
}
}else{
$item.=$item.=<<<EOD
{
"f": "{$mysqli->connect_errno}",
"m": "{$mysqli->connect_error}"
},
EOD;
}
}
}else{
$item.=$item.=<<<EOD
{
"f": "{$mysqli->connect_errno}",
"m": "{$mysqli->connect_error}"
},
EOD;
}
?>
{
"items": [
<?php echo $item;?>
[
}
<?php
}
?>
答案 0 :(得分:0)
如果您使用格式错误的json格式回复,则可能会发生这种情况。 尝试简单地将数据放入数组/对象中,然后使用json_encode 在它上面:
<?php
$data = [];
$data["f"] = "value1";
$data["m"] = "value2";
echo json_encode($data);
?>
答案 1 :(得分:0)
虽然没有它你通常很好,你可以并且应该设置Content-Type标题:
<?php
$data = array();
$files = array();
$allFiles = scandir($_REQUEST['dir_name']);
$files = array_diff($allFiles, array('.', '..'));
foreach($files as $key=>$file){
$data[$key]['name'] = $file;
if(is_dir(_REQUEST['dir_name'].'/'.$file)){
//Get small image of folder here and store that in $data[$key]['preview']
$data[$key]['type'] = 'dir';
}
else{
$extension = substr(strrchr($filename, "."));
$data[$key]['type'] = $extension;
switch ()$extension) {
case 'jpeg' : {
//Get small thumbnail of jpeg image here and store that in $data[$key]['preview'];
}
case 'png' : {
//Get small thumbnail of png image here and store that in $data[$key]['preview'];
}
case 'pdf' : {
//Get small thumbnail of pdf here and store that in $data[$key]['preview'];
}
case 'rar' : {
//Get small thumbnail of default .rar image here and store that in $data[$key]['preview'];
}
}
}
}
echo json_encode($data);
?>
注意:这是从另一篇文章中获取的 (Returning JSON from a PHP Script)