Javascript 获取jQquery Ajax Response的长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11358138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:37:05  来源:igfitidea点击:

Get the length of jQquery Ajax Response

javascriptjqueryajax

提问by under5hell

I need to count the length of an Ajax response done in jQuery. The response is in JSON format and only contains a single string. I get the value but have no idea how to count the length of this string.

我需要计算在 jQuery 中完成的 Ajax 响应的长度。响应采用 JSON 格式,仅包含一个字符串。我得到了值,但不知道如何计算这个字符串的长度。

Here's my code :

这是我的代码:

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?
    }
});

Here's the structure of the response header:

这是响应头的结构:

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

回答by fedmich

Do an if condition then convert it to string first, then count the length as needed.

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

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

回答by Niranda

Or convert your value (I guess it is an integer) to string:

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

tempId.toString().length

回答by Surekha

tempId.String.lengthworked for me!

tempId.String.length为我工作!

回答by Dinesh Gopal Chand

If you know the response is not an object then

如果您知道响应不是对象,那么

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

will work well.

会很好用。

but if response will be in the form of Object like

但如果响应将采用 Object 的形式,例如

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

I would suggest use below code

我建议使用下面的代码

success: function(response) {
     length=0;
     if(response){       
        length=JSON.stringify(response).length;
     }
    console.log(length)
}

I think this code will work like a charm for you.

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