如何在JavaScript中计算Content-Length

function LikesDislikes () { $.ajax({ url: 'http://gdata.youtube.com/feeds/api/videos/keDZXXDxK1c/ratings', type:"POST", data: '   ', 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

如规格中所述

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

请看这个问题JavaScript中的字符串长度(以字节为单位) 。

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

 function LikesDislikes () { var data = '   '; $.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); } }); } 

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

句法

 Content-Length:  

指令

  The length in decimal number of octets. 

内容长度计算

  • 如果请求体是String,则可以简单地使用body的长度。
  • 如果请求正文是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