Lei Zhao
Lei Zhao

Reputation: 442

How do I POST raw JSON data without using AJAX?

I have an API endpoint that I want to call. 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?

Upvotes: 0

Views: 2698

Answers (1)

Shawn K
Shawn K

Reputation: 778

You could do that with ajax or raw 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. 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. 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...

  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));

Upvotes: 2

Related Questions