简体   繁体   中英

Ajax POST request on https in vanilla js

I'm trying to make an Ajax POST request in vanilla js (the site dosen't have jquery). I've tried to do something like this, but can't make it work.

var params = { name: "Test"};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.testurl.com/api/test/save', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
        response = JSON.parse(xhr.responseText);
        console.log(reponse);
    }

};
xhr.send(JSON.stringify(params));

I get this error GET https://www.testurl.com/login.aspx?ReturnUrl=%2fapi%2ftest%2fsave 404 (Not Found)

Do anyone have any idea how to make the AJAX post request work with https in vanilla js?

Try following:

$(function () {
      // event handler
      function reqListener () {
        console.log( this.response );
      }

      // get new XHR object
      var newXHR = new XMLHttpRequest();

      // bind our event listener to the "load" event.
      // "load" is fired when the response to our request is completed and without error.
      newXHR.addEventListener( 'load', reqListener );

      // go to http://requestb.in/1k6rql51?inspect to view your request!
      newXHR.open( 'POST', 'http://requestb.in/1k6rql51' );
      //             ^-- IMPORTANT: to send data to the server with it appearing in the url use 'POST'


      // the object below can be crafted in any fashion. In the end you want an Object Literal with your data stored on it.
      var jsonData = { name: 'Ray', password: 'NIGERA RULES?!' };

      // HTTP Protocol can only work with strings when transmitting data over the internet.
      // JSON is a class and .stringify is a class-method. We use it to format
      // the Javascript Data, which lives in memory, to JSON string.
      var formattedJsonData = JSON.stringify( jsonData  );

      // INSPECT WHAT YOU EXPECT, compare the two.
      console.log( jsonData );
      console.log( JSON.parse( formattedJsonData ) );

      // send it off
      newXHR.send( formattedJsonData );
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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