javascript - .length 计算字符数,而不是数组长度

标签 javascript php arrays

我想计算 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)}
};

这是我得到的图片。我想获取项目数,在本例中为 2。

最佳答案

无论你从 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/

相关文章:

javascript - jQuery:分别不向标签添加类或立即删除它

javascript - 使用 Dexie,我可以获取表中数组字段具有特定值作为其元素之一的所有对象吗?

javascript - HTML Hidden 控件是否有任何事件?比如onchange之类的?

php - Apache Solr 搜索自动完成

c - 如何将空白数组排序到顶部以便我可以删除它们

mysql - 收到sequelize的响应后修改JSON

javascript - react redux 中组件和容器的区别

PHP session 获取正确值

javascript - 使用 CryptoJS 解密 openssl_seal 中的密文

java - HashMap 有支持数组,那为什么它是无序的