Home > Article > Web Front-end > Steps to send ajax request data using native javascript
Note: The request address is your own project address, please change it yourself.
This is just a simple use of native XMLHttpRequst. Later, I will post how to encapsulate native ajax to implement jequery's ajax
const xhr = new XMLHttpRequest();
xhr.open('PUT','http://118.24.84.199:8080/sm/accept/list',false);
xhr.setRequestHeader('token','515b8c62-ddf4-41ef-a7c8-93957e1c589e'); xhr.setRequestHeader('Accept','application/json'); xhr.setRequestHeader('Content-Type','application/json');
Note: The data here needs to be processed as a json file and processed using JSON.stringify.
let data = { page:1, pageSize:10, }; data = JSON.stringify(data); xhr.send(data);
If the data is a synchronous request: process the data directly after the send() statement.
console.log(xhr.response);
But in general, data requests are asynchronous, so the onreadystatechange event must be used to process the data.
Print the data after receiving it.
xhr.onreadystatechange = function(event){ if (xhr.readyState == 4){ if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){ console.log(JSON.parse(xhr.response)); } else { console.log("Request was unsuccessful: " + xhr.status); } } };
Related articles:
How to use native JS to implement Ajax’s GET POST request
Example explanation using native JavaScript processing AJAX request method
Related videos:
Ajax principle detailed video tutorial
The above is the detailed content of Steps to send ajax request data using native javascript. For more information, please follow other related articles on the PHP Chinese website!