Send POST data using XMLHttpRequest

前端 未结 13 1509
说谎
说谎 2020-11-21 04:27

I\'d like to send some data using an XMLHttpRequest in JavaScript.

Say I have the following form in HTML:

<         


        
13条回答
  •  我寻月下人不归
    2020-11-21 04:57

    Use modern JavaScript!

    I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.

    const url = "http://example.com";
    fetch(url, {
        method : "POST",
        body: new FormData(document.getElementById("inputform")),
        // -- or --
        // body : JSON.stringify({
            // user : document.getElementById('user').value,
            // ...
        // })
    }).then(
        response => response.text() // .json(), etc.
        // same as function(response) {return response.text();}
    ).then(
        html => console.log(html)
    );

    In Node.js, you'll need to import fetch using:

    const fetch = require("node-fetch");
    

    If you want to use it synchronously (doesn't work in top scope):

    const json = await fetch(url, optionalOptions)
      .then(response => response.json()) // .text(), etc.
      .catch((e) => {});
    

    More Info:

    Mozilla Documentation

    Can I Use (96% Nov 2020)

    David Walsh Tutorial

提交回复
热议问题