获取jQuery Ajax响应的长度

时间:2012-07-06 07:57:04

标签: javascript jquery ajax

我需要计算在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

4 个答案:

答案 0 :(得分:13)

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

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

答案 1 :(得分:7)

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

tempId.toString().length

答案 2 :(得分:0)

tempId.String.length为我工作了!

答案 3 :(得分: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)
}

我认为这段代码对您来说就像一个魅力。