【发布时间】:2019-02-08 14:50:21
【问题描述】:
我使用 ajax 从 php 中的 sql 查询中获取行数 (COUNT(*))。
Firefox-Network 选项卡中的 JSON 返回是:
[{"number":2}],
(2 不带引号)。
但在“ajax 成功”中,当我尝试从 data[0]["number"] 或 data.length 获取值 (2) 时,它返回“undefined”。
仅当我将 JSON 解析为对象时才有效。
$.ajax({
url: 'queries.php?q=count',
type: 'post',
//data: data,
datatype: 'json',
success: function(data) {
//var dataobject = jQuery.parseJSON(data);
//console.log(dataobject);
//var var2 = dataobject[0].number; ---->THIS WORKS!
//alert(JSON.parse(data).length); ---->THIS WORKS!
//console.log(data.length); ---->Undefined
console.log(typeof data); ---->string
console.log(data[0]["number"]);---->Undefined,i want this to work!!!
}
});
我在 php 中使用的 SQL 是:
switch ($_GET["q"]) {
case "count":
$sql = "SELECT count(*) as number from
(SELECT Employees.emp_username, .............
where Employees.emp_username = ? and Year(emp)=2016 and Month(emp)= MONTH(getdate()) ) as rows1 ";
$stmt = sqlsrv_prepare( $conn, $sql , array(&$_SESSION["username"] ));
break;
default: header("Location: index.php"); }
if( !$stmt ) { die( print_r( sqlsrv_errors(), true)); }
sqlsrv_execute($stmt);
$rows = array();
if(sqlsrv_execute($stmt)){
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
$rows[] = $row; }
} else{
die( print_r( sqlsrv_errors(), true));
}
print json_encode($rows);
【问题讨论】:
-
在 php 中您必须使用 json_encode 发送数据,或者您必须在 javascript 中解析 JSON,因为 javascript 不知道它是一个 json 对象,并且将其作为从 php 返回的字符串。
-
我看到返回的 JSON 是一个字符串。但是我在其他应用程序中使用了这个 ajax-php-sql 代码,它没问题,不需要先解析返回的 JSON。当我在 Jquery Datatables 中使用它时也会发生同样的情况,我不在那里解析任何东西。我发现问题出在查询 php 文件中,其中 JSON 输出应该或不应该是一个对象???如果我写 header('Content-type: application/json; charset=utf-8');在打印 json_encode($rows);它无需解析 JSON 即可工作。
-
我的目标是指出错误问题在哪里,在哪段代码中?我相信 print json_encode($rows);足以让 JSON 作为对象返回。
-
Mandeep,我使用“print json_encode($rows);”在php文件的最后一行里面有sql查询。这还不足以返回一个有效的json数组吗?有人解释为什么data[0][number]不起作用?