如何在JavaScript中计算Content-Length

时间:2013-07-20 13:31:57

标签: javascript ajax jquery

function LikesDislikes () {

    $.ajax({
        url: 'http://gdata.youtube.com/feeds/api/videos/keDZXXDxK1c/ratings',
        type:"POST",
        data: '<?xml version="1.0" encoding="UTF-8"?>
            <entry xmlns="http://www.w3.org/2005/Atom"
                   xmlns:yt="http://gdata.youtube.com/schemas/2007">
                <yt:rating value="like"/>
            </entry>',
        headers: {
            "Content-Type":"application/atom+xml",
            "Content-Length":,
            "Authorization":"Bearer ya29.AHES6ZQ59RrQgujZmIjssBdYlwwLVrpCodnirdLROi7-g7U",
            "X-GData-Key":"key=AIzaSyAPrtP2Tq4m5WVInCvCWptVAKPhQ4SQNZA",
            "GData-Version":"2"
        },
        // Content-Type:"application/atom+xml",
        error: function() { alert("No data found."); },
        // contentType: "text/xml",
        success: function (response) {
            alert('response:' + response);
        }
   });

}

如何计算上述代码中的Content-Length

2 个答案:

答案 0 :(得分:6)

specs

所述
  

Content-Length实体标题字段指示的大小   entity-body,以十进制数字表示的OCTET

请查看此问题String length in bytes in JavaScript

基本上如果你的数据只包含ASCII字符,一切都应该很容易

function LikesDislikes () {

    var data = '<?xml version="1.0" encoding="UTF-8"?>
    <entry xmlns="http://www.w3.org/2005/Atom"
           xmlns:yt="http://gdata.youtube.com/schemas/2007">
        <yt:rating value="like"/>
    </entry>';

    $.ajax({
        url: 'http://gdata.youtube.com/feeds/api/videos/keDZXXDxK1c/ratings',
        type:"POST",
        data: data,
        headers: {
            "Content-Type":"application/atom+xml",
            "Content-Length": data.length,
            "Authorization":"Bearer ya29.AHES6ZQ59RrQgujZmIjssBdYlwwLVrpCodnirdLROi7-g7U",
            "X-GData-Key":"key=AIzaSyAPrtP2Tq4m5WVInCvCWptVAKPhQ4SQNZA",
            "GData-Version":"2"
        },
        // Content-Type:"application/atom+xml",
        error: function() { alert("No data found."); },
        // contentType: "text/xml",
        success: function (response) {
            alert('response:' + response);
        }
    });
}

答案 1 :(得分:0)

Content-Length 实体标头指示发送给收件人的实体主体的大小(以字节为单位)。

语法

Content-Length: <length>

指令

<length>
The length in decimal number of octets.

内容长度计算

  • 如果请求正文是一个字符串,您可以简单地使用正文的长度。
  • 如果请求正文是JSON,则可以对正文进行字符串化。

const requestBody =
{
  data: 
  {
     ...
  }
};
xhr.setRequestHeader("Content-Length", JSON.stringify(requestBody).length.toString());

了解详情: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Length