Home  >  Article  >  Web Front-end  >  Steps to send ajax request data using native javascript

Steps to send ajax request data using native javascript

php是最好的语言
php是最好的语言Original
2018-08-03 14:14:403580browse

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

The first step: Create an xhr object.

const xhr = new XMLHttpRequest();

The second step: open() settings.

xhr.open('PUT','http://118.24.84.199:8080/sm/accept/list',false);

Step 3: Set the headers required by the interface.

xhr.setRequestHeader('token','515b8c62-ddf4-41ef-a7c8-93957e1c589e');
xhr.setRequestHeader('Accept','application/json');
xhr.setRequestHeader('Content-Type','application/json');

Step 4: Send request data.

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

It has been sent here, and you can check the request status in the browser's network request.

Steps to send ajax request data using native javascript

But the data has not been processed in the page yet

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn