我使用 ajax 从 php 中的 sql 查询中获取行数 (COUNT(*))。
Firefox-Network 选项卡中的 JSON 返回是:
[{“2号}],
(2 没有引号)。
但是在“ajax 成功”中,当我尝试从 data[0]["number"] 或 data.length 获取值 (2) 时,它返回“未定义”。
它仅在我将 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);