dongyan2445 2017-02-23 06:23
浏览 45
已采纳

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

I want to count the items of an array returned by json. When I use response.length, it counts all the characters in the array(I guess so) while what I want it to do is to count how many items are there in the array. Same method works in another pages, just not with this one.

This is the php code:

            ...$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 code:

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)}
};

Here is a picture of what I get. I want to get the count of items, which in this case is 2.

  • 写回答

6条回答 默认 最新

  • duanpacan2583 2017-02-23 06:27
    关注

    Whatever you send back from PHP is always a string.
    jQuery will however parse that string for you automagically, if you either send the correct headers, or tell it that it's JSON in the settings

    $.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
    

    And use the console for debugging

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划