繁体   English   中英

PHP json_encode到AJAX,未定义

[英]PHP json_encode to AJAX, undefined

我是AJAX的新手,我只是想通过AJAX从PHP到HTML显示数据库结果。 加载页面时,控制台日志上显示“ undefined”。 HTML,PHP和JS文件彼此分开。

这是我的JS代码:

$(document).ready(function(){

$.ajax({

    type: "GET",
    url:  "xaja.php",
    dataType: "json",
    contentType: "application/json; charset=utf-8",

    success: function(data){
        console.log(""+data.name);
    },
    error: function(e){
        alert("Error:\n"+e);
    }

});

});

这是我的PHP代码:

<?php

$json = array(

'username' => '',
'name' => '',
'loc' => ''

);


$sql = "Select * from tbluser";
$query = mysql_query($sql, $conn);
$result = mysql_fetch_assoc($query);

do{
    $json['username'] = $result['username'];
    $json['name'] = $result['name'];
    $json['loc'] = $result['location'];
    echo json_encode($json);
    $result = mysql_fetch_assoc($query);

}
while($result);

?>

我在这里想念什么吗? 提前致谢!

您正在输出多个json字符串。 为了解析您的响应,它必须是单个字符串。 尝试以下方法:

$results = array();
do{
    $json['username'] = $result['username'];
    $json['name'] = $result['name'];
    $json['loc'] = $result['location'];
    $results[] = $json;
    $result = mysql_fetch_assoc($query);
}
while($result);
echo json_encode($results);

为什么不采用传统方式?

$sql = "Select * from tbluser";
$query = mysql_query($sql, $conn);

if ($result = mysql_fetch_assoc($query) ) {
    $json['username'] = $result['username'];
    $json['name'] = $result['name'];
    $json['loc'] = $result['location'];
    echo json_encode($json);
}

或者如果您需要array数组:

$json = array();
$sql = "Select * from tbluser";
$query = mysql_query($sql, $conn);

while ($result = mysql_fetch_assoc($query) ) {
    $json[] = array($result['username'], $result['name'], $result['location']);
}
echo json_encode($json);

返回JSON时,它应该是一个单一的结构,而不是为每一行输出一个数组,而应该构建该数组并将其输出一次。

$json = array();
do {
    $json[]=$result;
    $result = mysql_fetch_assoc($query);
} while($result);
echo json_encode($json);

它将每行显示为一个命名结构( [{username:"",name:"",location:""},{}..]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM