Give you three different ways to implement GET and POST requests

Posted by waradmin on Fri, 04 Mar 2022 10:00:06 +0100

Article catalogue

preface

It's a new beginning. After a happy holiday, I began to invest in the tense and exciting learning time. Xiaobian summarizes three methods of sending requests that Xiaobian has learned. Interested friends, come and have a look! Learn! Learn!!!!!

 

1. Ajax in jQuery

First of all, before we begin to explain the knowledge points, we need to know what Ajax is?  

So what is Ajax?

The full name of Ajax is Asynchronous JavaScript And XML

Simple understanding: using XMLHttpRequest object to interact with the server in web pages is Ajax

After a brief introduction to what Ajax is, let's start today's sharing!

1.1,$.get()

$. get() syntax structure: $ get(url,[data],[callback])

Attribute introduction:

  • url: string (character type) required, the address of the resource to be requested
  • data: object object; optional; parameter carried during resource request
  • Callback: function, optional or not. It is the callback function when the request is successful

 $. get() initiates a GET request without parameters:

First, we need to reference our jQuery JS file

<script src="jquery.js"></script>
<body>
    <button id="btnGET">Initiate without parameters get request</button>
    <script>
        $(function() {
            $('#btnGET').on('click', function() {
                $.get('http://www.liulongbin.top:3006/api/getbooks', function(res) {
                    console.log(res);
                })
            })
        })
    </script>
</body>

$. get() initiates a GET request with parameters:

<body>
    <button id="btnINfo">Initiate with parameters get request</button>
    <script>
        $(function() {
            $('#btnINfo').on('click', function() {
                $.get('http://www.liulongbin.top:3006/api/getbooks', {
                    id: 1
                }, function(res) {
                    console.log(res);
                })
            })
        })
    </script>
</body>

1.2,$.post() 

$. post() syntax format: $ post(url,[data],[callback]) 

$. post() initiates a POST request:

<body>
    <button id="postBtn">launch POST request</button>
    <script>
        $(function() {
            $('#postBtn').on('click', function() {
                $.post('http://www.liulongbin.top:3006/api/addbook', {
                    bookname: 'Water Margin',
                    author: 'Shi Naian',
                    publisher: 'Tianjin book publishing house'
                }, function(res) {
                    console.log(res);
                })
            })
        })
    </script>
</body>

1.3,$.ajax() 

$. ajax() syntax format:

$.ajax({
    type:'',//Request mode, such as get or post
    url: '',//Requested URL address
    data:{},//Data to be carried in this request
    success:function(res){}//Callback function after successful request
}) 

$. ajax() initiates a GET request:

$.ajax({
  type: 'get',
  url: 'http://www.liulongbin.top:3006/api/getbooks',
  data: { id: 1 }
  success: function(res) {
    console.log(res)
}
})

 $. ajax() initiates a POST request:

$.ajax({
  type: 'post',
  url: 'http://www.liulongbin.top:3006/api/getbooks',
  data: { 
     bookname: 'Water Margin',
     author: 'Shi Naian',
     publisher: 'Shanghai book publishing house'
 },
  success: function(res) {
    console.log(res)
}
})

In Ajax, you only need to set the type attribute to change your request mode. If you want to implement the GET request, change the type attribute to 'GET' or 'GET'. If it is a post request, change the type attribute to 'post' or 'post'.  

2. XMLHttpRequest mode

Old rules! Before we begin to explain our knowledge, we still need to know what XMLHttpRequest is?

XMLHttpRequest (XHR for short) is a JavaScript object provided by the browser, through which you can request data resources on the server.

After understanding, let's start our study!  

2.1. Initiate GET request

To send a GET request:

  1. Create xhr object
  2. Call XHR The open() function specifies the request method and URL address
  3. Call XHR The send() function} initiates an Ajax request
  4. Monitor XHR Onreadystatechange event

Initiate GET request without parameters:

<script>
        // 1. Create XHR object
        var xhr = new XMLHttpRequest()
            // 2. Call the open function
        xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks')
            // 3. Call the send function
        xhr.send()
            // 4. Listen to onreadystatechange event
        xhr.onreadystatechange = function() {
            // Listen to the request state readyState of xhr object; Server response status
            if (xhr.readyState === 4 && xhr.status === 200) {
                // Get the data of the server response
                console.log(xhr.responseText)
            }
        }
    </script>

Initiate GET request with parameters:

<script>
    var xhr = new XMLHttpRequest()
    xhr.open('GET', 'http://www.liulongbin.top:3006/api/getbooks?id=1')
    xhr.send()
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)
      }
    }
  </script>

2.2. Initiate POST request

To send a POST request:

  1. Create xhr object
  2. Call XHR Open() function
  3. Set the content type property (fixed writing method) and call the setRequestHeader function
  4. Call XHR Send() and specify the data to be sent
  5. Monitor XHR Onreadystatechange event
<script>
    // 1. Create xhr object
    var xhr = new XMLHttpRequest()
    // 2. Call the open function
    xhr.open('POST', 'http://www.liulongbin.top:3006/api/addbook')
    // 3. Set the content type attribute
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
    // 4. Call the send function
    xhr.send('bookname=Water Margin&author=Shi Naian&publisher=Shanghai book publishing house')
    // 5. Listening events
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4 && xhr.status === 200) {
        console.log(xhr.responseText)
      }
    }
  </script>

3,Axios

Or the familiar taste! Before we start, let's see what Axios is?

Axios is a library that focuses on network data requests. Compared with the native XMLHttpRequest object, Axios is simple and easy to use. Compared with jQuery, it is more urgent and lightweight, and only focuses on network data requests

So we need to reference Axios JS file.

3.1. Initiate GET request

Syntax format: Axios Get ('url ', {params: {/ * parameter * /}}) then(callback)

<body>
    <button id="btn3">Direct use axios launch GET request</button>
    <script>
        document.querySelector('#btn3').addEventListener('click', function() {
            var url = 'http://www.liulongbin.top:3006/api/get'
            var paramsData = {
                name: 'Iron Man',
                age: 35
            }
            axios({
                method: 'GET',
                url: url,
                params: paramsData
            }).then(function(res) {
                console.log(res.data)
            })
        })
    </script>
</body>

3.2. Initiate POST request

Syntax format: Axios Post ('url ', {/ * parameter * /}) then(callback)

<body>
    <button id="btn4">Direct use axios launch POST request</button>
    <script>
        document.querySelector('#btn4').addEventListener('click', function() {
            axios({
                method: 'POST',
                url: 'http://www.liulongbin.top:3006/api/post',
                data: {
                    name: 'Wahaha',
                    age: 18,
                    gender: 'female'
                }
            }).then(function(res) {
                console.log(res.data)
            })
        })
    </script>
</body>

summary

That's all for today's sharing! You should study hard!

 

Topics: Javascript Front-end Ajax