2017-02-23 29 views
1

我想計算由json返回的數組的項目。當我使用response.length時,它會統計數組中的所有字符(我猜是這樣),而我想要的是計算陣列中有多少項。同樣的方法適用於另一個頁面,而不是這個。.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的項目數。

+1

解析對象的響應,然後得到它的計數。 –

+1

您是否嘗試過解析JSON以獲取實際的數組?或者在調用'$ .post()'時指定''json''作爲數據類型,jQuery將爲你解析它。 – nnnnnn

+1

'JSON.parse(response)',或者告訴jQuery你期望得到一個JSON響應。 – Svenskunganka

回答

3

無論您從PHP發回的東西都是字符串。然而
jQuery將解析字符串爲你自動的,如果你無論是發送正確的頭,或者告訴它,它的JSON在設置

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

使用控制檯進行調試

2

您需要解析響應var response = JSON.parse(response),然後response.length將返回所需的結果。

2
var getData = { 
        date: $("#displaydate").val(), 
        operation:"getData" 
       } 

       $.post("printoperations.php", getData).done(function(response) { 
        if (response.val != 0){ 

         alert("so far so good") 
         var responseArray = JSON.parse(response) 
         alert(responseArray) 
         alert(responseArray.length)} 
}; 
+0

@adeneo非常感謝。這是一個錯字。糾正它 –

1

看來你正試圖找到字符串的長度。相反,嘗試alert(typeof response),如果它給出了字符串,那麼在做任何事情之前,先用JSON.parse(response)解析它到JSON然後再嘗試。

0

JSON.parse(response)這樣做。感謝所有答案!

0

你應該把這個

header('Content-Type: application/json');

在服務器端PHP查詢。