我想计算 json 返回的数组的项目。当我使用 response.length
时,它会计算数组中的所有字符(我猜是这样),而我想要它做的是计算数组中有多少项。相同的方法适用于其他页面,但不适用于此页面。
这是PHP代码:
...$response[] = array("id" => $row['appid'],
"hour" => $row['hour'],
"tname" => $tname,
"tsurname" => $tsurname,
"cname" => $cname,
"csurname" => $csurname,
"cgsm" => $cgsm,
"cemail" => $cemail,
"cdept" => $cdept,
"cdeg" => $cdeg,
"purpose" => $purpose,
"clientnotshown" => $row['clientnotshown']);
};
if(isset($response)){
echo json_encode($response);
} else {
$response = array("val" => 0);
echo json_encode($response);
};
Javascript 代码:
function updateTable() {
var getData = {
date: $("#displaydate").val(),
operation:"getData"
}
$.post( "printoperations.php", getData).done(function( response ) {
if (response.val != 0){
alert("so far so good")
var arrayLength = response.length
alert(response)
alert(arrayLength)}
};
最佳答案
无论你从 PHP 发回什么总是一个字符串。
但是,如果您发送正确的 header ,或者在设置中告诉它它是 JSON,jQuery 会自动为您解析该字符串
$.post("printoperations.php", getData, function(response) {
if (response.val != 0) {
console.log("so far so good")
var arrayLength = response.length
console.log(response)
console.log(arrayLength)
}
}, 'json'); // <- here
并使用控制台进行调试
关于javascript - .length 计算字符数,而不是数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42408476/