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
4

4 回答 4

15

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

success: function(response) {
    if(response){       
      alert( (response + '').length );
    }
}
于 2012-07-06T08:12:22.223 回答
8

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

tempId.toString().length
于 2012-07-06T08:37:48.107 回答
0

tempId.String.length为我工作!

于 2012-12-31T20:06:15.287 回答
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)
}

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

于 2019-10-15T10:12:39.150 回答