简体   繁体   English

如何在不使用AJAX的情况下发布原始JSON数据?

[英]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: 原因如下:

  • I can't use AJAX because the response of this API is a file to download. 我无法使用AJAX,因为此API的响应是要下载的文件。 So I probably need to create a hidden iframe and send regular POST request from there. 因此,我可能需要创建一个隐藏的iframe并从那里发送常规的POST请求。
  • I need to POST data as a raw JSON string, not in form data. 我需要将数据作为原始JSON字符串发布,而不是表单数据。 The API does not accept key value pairs. API不接受键值对。 So I can't just create an HTML form and submit it. 因此,我不能只是创建一个HTML表单并提交它。
  • This is not my API. 这不是我的API。 I can't change it. 我不能改变

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM