Ajax foundation — learning record (3)

Time:2021-4-23

Ajax in jquery

$.ajax()

Overview of $. Ajax () method

Function: send Ajax request.

 $.ajax({
     type: 'get',
     url: 'http://www.example.com',
     data: { name: 'zhangsan', age: '20' },
     //data: 'name=zhangsan&age=20'
     contentType: 'application/x-www-form-urlencoded',
     //contentType: 'application/json'
     beforeSend: function () { 
         return false
     },
     success: function (response) {},
     error: function (xhr) {}
});

BeforeSend method description

$.ajax({
    //Request method
    type: 'post',
    //Request address
    url: '/user',
    // call before request is sent
    beforeSend: function () {
        Alert ('request will not be sent ')
        //The request will not be sent
        return false;
    },
    //The function is called after the request is successful
    success: function (response) {
        //Response is the data returned by the server
        //Method will automatically convert the JSON string to a JSON object
        console.log(response);
    }
})

Function: send JSON request.

$.ajax({
    url: 'http://www.example.com',
    //Specifies that a JSON request is currently sent
    dataType: 'jsonp',
    //Modify the name of the callback parameter
    jsonp: 'cb',
    //Specifies the function name
    jsonCallback: 'fnName',
    success: function (response) {} 
})

Serialize method

Function: automatically splice the data in the form into string type parameters

var params = $('#form').serialize();
// name=zhangsan&age=30

$.get()、$.post

Overview of $. Get(), $. Post() methods

Function: the $. Get method is used to send get requests, and the $. Post method is used to send post requests.

$.get('http://www.example.com', {name: 'zhangsan', age: 30}, function (response) {}) 
$.post('http://www.example.com', {name: 'lisi', age: 22}, function (response) {})

Ajax global events in jquery

As long as an Ajax request is sent in the page, the corresponding global event will be triggered

. ajaxstart() // triggered when the request starts to be sent
. ajaxcomplete() // triggers when the request completes

NProgress

Guan Xuan: nanoscale progress bar, using realistic trickle animation to tell users what is happening!

<link rel='stylesheet' href='nprogress.css'/>
<script src='nprogress.js'></script>
NProgress.start ();  //  The progress bar starts to move 
NProgress.done ();   //  Progress bar end movement

Restful style API

Review of traditional request address

GET  http://www.example.com/getUsers          //Get user list
GET  http://www.example.com/getUser?id=1      //For example, get the information of a user
POST  http://www.example.com/modifyUser       //Modify user information
GET  http://www.example.com/deleteUser?id=1   //Delete user information

Overview of restful API

A set of specifications for design requests.

Get: get data
Post: add data
Put: update data
Delete: delete data

Implementation of restful API

Each request address should correspond to a resource
users => /users
articles => /articles

GET:http://www.example.com/usersGet user list data
POST:http://www.example.com/usersCreate (add) user data
GET:http://www.example.com/users/1Get the user information with user ID 1
PUT:http://www.example.com/users/1Modify user information with user ID 1
DELETE:http://www.example.com/users/1Delete user information with user ID 1

be careful: traditional HTML form submission does not support put and delete, but it does in Ajax

Server side:

//Get user list information
app.get('/users', (req, res) => {
    res.send ('the current route is to obtain user list information ');
});

//The route to get the specific information of a user
app.get('/users/:id', (req, res) => {
    //Get the user ID passed by the client
    const id = req.params.id;
    res.send ('at present, we are getting user information with ID ${ID} ');
});

//Delete a user
app.delete('/users/:id', (req, res) => {
    //Get the user ID passed by the client
    const id = req.params.id;
    res.send ('at present, we are deleting user information with ID ${ID} ');
});

//Modify a user's information
app.put('/users/:id', (req, res) => {
    //Get the user ID passed by the client
    const id = req.params.id;
    res.send ('at present, we are modifying the ID to ${ID} user information ');
});

client:

<script type="text/javascript">
    //Get user list information
    $.ajax({
        type: 'get',
        url: '/users',
        success: function (response) {
            console.log(response)
        }
    })

    //Get the user information with ID 1
    $.ajax({
        type: 'get',
        url: '/users/1',
        success: function (response) {
            console.log(response)
        }
    })

    //Delete the user information with ID 10
    $.ajax({
        type: 'delete',
        url: '/users/10',
        success: function (response) {
            console.log(response)
        }
    })

    //Modify the user information with ID 1
    $.ajax({
        type: 'put',
        url: '/users/10',
        success: function (response) {
            console.log(response)
        }
    })
</script>

XML Foundation

What is XML

The full name of XML is extensible markup language, which stands for extensible markup language. Its function is to transmit and store data.

<students> 
     <student>
         <sid>001</sid>
         < name > Zhang San
         </student>
     <student>
         <sid>002</sid>
         < name > Wang Erya
         </student>
 </students>
app.get('/xml', (req, res) => {
    res.header('content-type', 'text/xml');
    res.send ('< message > < title > message Title < / Title > < content > message content < / content > < / message >')
});

XML DOM

XML DOM is an XML document object model, which is a set of API defined by W3C organization to operate XML document objects. The browser parses the XML document into a document object model.

btn.onclick = function () {
    var xhr = new XMLHttpRequest();
    xhr.open('get', '/xml');
    xhr.send();
    xhr.onload = function () {
        //  xhr.responseXML  Get the XML data returned by the server
        var xmlDocument = xhr.responseXML;
        var title = xmlDocument.getElementsByTagName('title')[0].innerHTML;
        container.innerHTML = title;
    }
}

Recommended Today

Analysis of super comprehensive MySQL statement locking (Part 1)

A series of articles: Analysis of super comprehensive MySQL statement locking (Part 1) Analysis of super comprehensive MySQL statement locking (Part 2) Analysis of super comprehensive MySQL statement locking (Part 2) Preparation in advance Build a system to store heroes of the Three KingdomsheroTable: CREATE TABLE hero ( number INT, name VARCHAR(100), country varchar(100), PRIMARY […]