[英]How do I POST raw JSON data without using AJAX?
I have an API endpoint that I want to call. 我有一个要调用的API端点。 It seems an easy task but to my surprise, it isn't.
这似乎是一件容易的事,但令我惊讶的是,事实并非如此。 Here's why:
原因如下:
Now I'm stuck. 现在我被卡住了。 Is there anything else I can try?
还有什么我可以尝试的吗?
You could do that with ajax or raw XMLHttpRequest() 您可以使用ajax或原始XMLHttpRequest()来完成此操作
A few things already mentioned in the commments to your question that explain what's going on here. 问题的注释中已经提到的一些事情可以解释这里发生的事情。
First you need a request object. 首先,您需要一个请求对象。 Posting is no problemo, you'll pass the JSON payload you've gotta send on that last line there.
发布没有问题,您将在该行的最后一行传递要发送的JSON有效负载。 After the POST is successful you'll need to take the binary returned and make an Blob for the correct file type, an objecctUrl and finally a hidden link that you'll click for the user.
POST成功后,您需要获取返回的二进制文件,并为正确的文件类型创建一个Blob,一个objecctUrl以及最后一个为用户单击的隐藏链接。 Please note the download attribute.
请注意下载属性。 This lets modern browsers know it's a download link which let's the download roll.
这使现代浏览器知道这是一个下载链接,这就是下载清单。
I've probably got some of this code from stackoverflow... 我可能已经从stackoverflow中获得了一些这样的代码...
const xlsx = {};
const xhr = new XMLHttpRequest();
xhr.open('POST', '/data/some.ashx');
xhr.responseType = 'blob';
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function loadXLXS() {
let objectUrl;
if (this.status === 200) {
blob = this.response
csvURL = window.URL.createObjectURL(blob);
tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', workBookName);
tempLink.click();
}
};
xhr.send(JSON.stringify(xlsx));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.