获取 jQuery Ajax 响应的长度

10
我需要在jQuery中计算Ajax响应的长度。响应采用JSON格式,只包含一个字符串。我可以获取该字符串的值,但不知道如何计算该字符串的长度。
这是我的代码:
var tempId;
$.ajax({
    url: "<?=base_url();?>index.php/sell/decoder",
    type: "POST",
    data: {'str' : sometext},
    dataType: 'json',
    async: false,
    success: function(response) {
        tempId = response; // This gives me a return value as a string. For example = 153
        alert(tempId.length); // But this returns "undefined". What should I do to get the length?
    }
});

这是响应头的结构:

Connection  Keep-Alive 
Content-Length  2
Content-Type    text/html
Date    Fri, 06 Jul 2012 08:12:12 GMT
Keep-Alive  timeout=5, max=86
Server  Apache
X-Powered-By    PHP/5.3.10

2
你能展示一下响应的结构吗? - Teneff
如果你可以使用 alert(tempId.length);,为什么不也用 alert(tempId); 呢?同时你也可以使用 console.log(tempId) 在控制台中查看它。 - xdazz
执行console.log(response)并向我们展示结果。另外,为什么要使用async: false?不要这样做,因为同步请求可能会暂时锁定浏览器,在请求处于活动状态时禁用任何操作。 - Angel
1
在成功函数的第一行执行console.log(response)。并将输出显示为原样。我之所以这么说是因为你说响应是一个字符串,但在你的评论中你说它是153,这是一个整数。 "153" 将是字符串。这可能是一个打字错误,这就是为令我要求原样响应的原因。 - Amith George
正确,但你应该将逻辑移到ajax的success函数中,或者在success中进行函数调用,以充分利用ajax的异步特性。 - Angel
显示剩余4条评论
4个回答

15

进行if条件判断后,先将其转换为字符串,然后根据需要计算长度。

success: function(response) {
    if(response){       
      alert( (response + '').length );
    }
}

8

或者将您的数值(我猜是整数)转换为字符串:

tempId.toString().length

这是更优雅的解决方案。但是我注意到你那里有个错别字 :-)。谢谢。 - under5hell
是的,.toString() 是一个函数。 - kmkmkm
只有当 tempID 不是对象类型时,tempId.toString().length 才有效。[{name:'test'}].toString() 将返回 [object Object]。而 [{name:'test'}].toString().length 将返回 15。 - Dinesh Gopal Chand

0

tempId.String.length 对我有用!


0
如果您知道响应不是一个对象,则:
success: function(response) {
    if(response){       
      alert( (response + '').length );
    }
}

会很好地运作。

但如果响应以对象的形式返回,则如下:

[{name:'some-name',details:[....something]}]

我建议使用以下代码。
success: function(response) {
     length=0;
     if(response){       
        length=JSON.stringify(response).length;
     }
    console.log(length)
}

我认为这段代码对你来说会非常顺利。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接