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

.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条)

报告相同问题?