我只需要檢查我的響應對象中是否有一些非零結果,而不必運行循環($ .each或其他)並增加一個計數器(儘管在第一次迭代後我可以中斷計數)。我想我可以使用jQuery的$ .size(),如果有結果並且沒有結果,則返回1和0。我在http://api.jquery.com/size/搜索,但沒有找到確認。有任何想法嗎 ?如何使用jQuery ajax檢查json響應對象中的非零結果?
這裏是我的簡單的代碼 -
$.ajax({
type: "POST",
data: postdata,
async: false,
url: posturl,
dataType: "json",
success: function(response)
{
var results = response.allResults;
alert($(results).size()+" and "+results.length);
//alerts "0 and 0" - when no results
//alerts "1 and undefined" - when there are 1 or more results
}
});
在後端PHP邏輯 -
//some array with key value pairs
$results = $this->_something($idsArray);
echo json_encode(array("allResults" => $results));
更新
我已經嘗試與length
屬性,你可以在我的代碼中看到例如,當存在非零結果時,它會提示undefined
。
console.log(response.allResults);
當有非零結果
-
Object { 109="add_offline_pack_test", 110="add_offline_pack_test1", 111="add_offline_pack_test2", more...}
當沒有結果 -
[]
使用'results.length'應該可以。你是否嘗試在控制檯輸出'response'來檢查'response.allResults'等於什麼? – jabclab
我會看看通話返回的原始JSON。從你報告的結果來看,就像'array(「allResults」=> $ results)'返回'nil',而不是空數組,沒有結果,這看起來很奇怪。 –
剛查過日誌,查看我的更新 –