Javascript JQuery:获取JSON回复的长度?
在JQueryJavascript JQuery:获取JSON回复的长度?,javascript,jquery,ajax,json,Javascript,Jquery,Ajax,Json,在JQuerygetJSON调用中,我如何知道返回的JSON的长度 function refreshRoomList() { $.getJSON('API/list_rooms', function (rooms) { if (rooms.length > 0) { $("#existing-room-list").empty(); $("#join-existi
getJSON
调用中,我如何知道返回的JSON的长度
function refreshRoomList() {
$.getJSON('API/list_rooms',
function (rooms) {
if (rooms.length > 0) {
$("#existing-room-list").empty();
$("#join-existing-room").text("Join existing room:"); // this shouldn't be here
$.each(rooms, function (index, roomName) {
var newChild = sprintf('<li><a href="room?key=%s">%s</a></li>', index, roomName);
$("#existing-room-list").append(newChild);
});
}
else {
$("#join-existing-room").text("No rooms found.");
}
});
}
函数refreshRoomList(){
$.getJSON('API/列表\u房间',
功能(房间){
如果(房间长度>0){
$(“#现有房间列表”).empty();
$(“#加入现有文件室”).text(“加入现有文件室:”;//不应该在这里
$。每个(房间、功能(索引、房间名称){
var newChild=sprintf(“”,索引,房间名称);
$(“#现有房间列表”)。追加(新儿童);
});
}
否则{
$(“#加入现有房间”).text(“未找到房间”);
}
});
}
出于某种原因,这不起作用,但如果我将rooms.length>0
替换为true
,则会打印出完整的房间列表
如果
rooms
为空,则返回为{}
请尝试此方法,在您的情况下,它在为空时应为null:
if (rooms) {
如果房间是空的,则返回为{}
因此,它不是一个数组,而是一个对象。对象没有长度。只有一个。如果您想不表示任何内容,则使用null
而不是{}
。这样,您就可以使用if(rooms)
要了解更多关于JSON的信息,您可能会发现有用的信息。返回的JSON有效负载是方括号内的
[]
还是curly{}
?用户有什么问题。长度
?我想我用错了。看上面。哦,我以为那是讽刺。它是以对象文字语法返回的。@Rosarch:phew,现在我们排除了这些问题,看看返回null
是否不适合您。这看起来像是在我的最小初始测试中起作用。谢谢。@Rosarch:我想你需要更多的测试;)