Javascript 如何将数据体发送到 XMLHttpRequest 看起来像这样?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37654521/
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-23 20:34:33  来源:igfitidea点击:

How to Send a body of data to XMLHttpRequest that looks like this?

javascriptajaxxmlhttpxmlhttprequest

提问by noogui

How do I format this correctly?

我如何正确格式化?

var params = {
  "range":"Sheet1!A4:C4",
  "majorDimension": "ROWS",
  "values": [
    ["Hello World","123", "456"]
  ],
}

Then send it using POSTlike :

然后使用POST发送它,例如:

   var xhr = new XMLHttpRequest();
   xhr.open(method, url);
   xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
   xhr.onload = requestComplete;
   xhr.send(params);

I know Im going to encounter errors because there's a proper way of formatting my "request body". It looks like a mixture of array and JSON so Im asking for your help how to format it correctly.

我知道我会遇到错误,因为有一种正确的方式来格式化我的“请求正文”。它看起来像是数组和 JSON 的混合体,所以我请求您帮助如何正确格式化它。

回答by Vladu Ionut

var xhr = new XMLHttpRequest();
   xhr.open(method, url);
   xhr.setRequestHeader('Authorization', 'Bearer ' + access_token);
   xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
   xhr.onload = requestComplete;
   xhr.send(JSON.stringify(params));

It looks like you just needed to stringify your params before passing them to send()

看起来您只需要在将参数传递给 send() 之前对其进行字符串化

回答by El'Magnifico

Have you tried it out yet? You can't just assume that you are going to encounter errors. You wouldn't know unless you try. Try you first method, if it fails, you would have discovered a way that won't work. Then you find other ways that would work, that's how we learn. It is from the errors and failures that we learn not from the successes.

你试过了吗?你不能只是假设你会遇到错误。除非你尝试,否则你不会知道。尝试第一种方法,如果失败,您会发现一种行不通的方法。然后你会找到其他可行的方法,这就是我们学习的方式。我们是从错误和失败中学到的,而不是从成功中学到的。

That being said, if your method fails as you have assumed, try to use JSON.stringifyon the params before sending it just like this

话虽如此,如果您的方法失败了,请尝试JSON.stringify在发送之前使用参数,就像这样

xhr.send(JSON.stringify(params))

That should work.

那应该工作。