AJAX quick start learning (with interface learning) - laying the foundation for later vue learning


foreword

insert image description here
The disadvantage of this interaction is obvious. Any interaction with the server requires a refresh of the page, and the user experience is very poor.
Using Ajax, web applications can quickly present incremental updates on the user interface without reloading (refreshing) entire page.

AJAX = Asynchronous JavaScript and XML (asynchronous JavaScript and XML).

AJAX is a technology that can update parts of a web page without reloading the entire web page.
Ajax allows us to easily realize data interaction between web pages and servers.
Ajax is a general term for technology and a conceptual model . It includes many technologies and does not specifically refer to a certain technology. One of its important features is to allow partial refresh of the page.

The core of ajax is the JavaScript object XmlHttpRequest

If you want to request data resources on the server in the web page, you need to use the XMLHttpRequest object.
XMLHttpRequest (xhr for short) is a js member provided by the browser, through which data resources on the server can be requested.

Popular understanding: Ajax is the way to use the XMLHttpRequest object to interact with the server in the web page.

Pay special attention that ajax and xhr cannot be equated. Xhr is a way for js to implement ajax, and there are other ways.
The simplest usage var xhrObj = new XMLHttpRequest()


Typical application scenarios of Ajax

User name detection : When registering a user, dynamically detect whether the user name is occupied in the form of ajax
insert image description here
Search prompt : When entering a search keyword, dynamically load the search prompt list
insert image description here
data in the form of ajax Pagination display : When clicking on the page number value , in the form of ajax, dynamically refresh the table data according to the page number value

insert image description here

The XMLHttpRequest provided in the browser is more complicated to use. Generally,
jquery will encapsulate ajax into a function $.ajax(). We can directly use this function to execute the ajax request

Now you don't need jQuery, you use axios . Axios is an encapsulation of ajax technology based on promise. The usage of the two is basically the same, but individual parameters are different. Axios encapsulates some simpler ajax operations.
Axios is ajax, but ajax is not limited to axios.
More importantly, Vue.js recommends using axios to complete ajax requests .

Ajax encapsulated by jQuery is (request type (type), url, parameter (data), callback function (success: function () {}))

$.ajax({
    
    
   type: 'GET', // 请求的方式
   url:'http://www.liulongbin.top:3006/api/getbooks', // 请求的 URL 地址
   data: {
    
     id: 1 },// 这次请求要携带的数据
   success: function(res) {
    
     // 请求成功之后的回调函数
       console.log(res)
   }
})
$.ajax({
    
    
   type: 'POST', // 请求的方式
   url: 'http://www.liulongbin.top:3006/api/addbook',  // 请求的 URL 地址
   data: {
    
     // 要提交给服务器的数据
      bookname: '水浒传',
      author: '施耐庵',
      publisher: '上海图书出版社'
    },
   success: function(res) {
    
     // 请求成功之后的回调函数
       console.log(res)
   }
})

The concept of interface

When using Ajax to request data, the requested URL address is called the data interface (interface for short). At the same time, each interface must have a request method.

For example:

http://www.liulongbin.top:3006/api/getbooks  获取图书列表的接口(GET请求)
http://www.liulongbin.top:3006/api/addbook   添加图书的接口(POST请求)

The above are the two interfaces

Interface Test Tool

In order to verify whether the interface can be accessed normally, we often need to use interface testing tools to detect the data interface.
Benefits: The interface testing tool allows us to call and test the interface without writing any code.
insert image description here
Visit PostMan's official download website https://www.getpostman.com/downloads/, download the required installation program, and install it directly. (It is more convenient to see the ppt operation)
user interface

GET steps:
1. Select the request method
2. Fill in the requested URL address
3. Fill in the request parameters
4. Click the Send button to initiate a GET request
5. View the result of the server response
insert image description here
POST steps:
1. Select the request method
2. Fill in the request
3. Select the Body panel and check the data format
4. Fill in the data to be sent to the server 5.
Click the Send button to initiate a POST request
6. View the result of the server response

interface documentation

The interface document, as the name implies, is the description document of the interface , which is the basis for us to call the interface. A good interface document includes a description of the interface URL , parameters , and output content. We can easily know the function of the interface and how to call the interface by referring to the interface document.

Components of an interface document
An interface document can contain a lot of information, and can also be simplified as needed. However, a qualified interface document should include the following 6 items to provide a basis for calling the interface: 1. Interface name:
used to identify A brief description of each interface, such as the login interface, the interface for obtaining the book list, etc.
2. Interface URL : the calling address of the interface.
3. Calling method : the calling method of the interface, such as GET or POST.
4. Parameter format : The parameters that need to be passed by the interface. Each parameter must contain four items: parameter name, parameter type, whether it is required, and parameter description.
5. Response format : a detailed description of the return value of the interface, generally including data name, data type, and description.
6. Return example (optional): In the form of an object, enumerate the structure of the data returned by the server.
insert image description here
insert image description here
insert image description here

jQuery encapsulated ajax

Starting from jQuery 1.7, the on() function provides all the functions needed to bind event handlers, and is used to uniformly replace the previous event functions such as bind(), delegate(), live(), etc.
Ajax instance encapsulated in jQuery:

$('tbody').on('click', '.del', function() {
    
    
    // 2. 获取要删除的图书的 Id
    var id = $(this).attr('data-id')
    $.ajax({
    
     // 3. 发起 ajax 请求,根据 id 删除对应的图书
        type: 'GET',
        url: 'http://www.liulongbin.top:3006/api/delbook',
        data: {
    
     id: id },
        success: function(res) {
    
    
            if (res.status !== 200) return alert('删除图书失败!') 
            getBookList() // 4. 删除成功后,重新加载图书列表
        }
    })
})

But no one uses jQuery now, it’s all vue, so please skip the syntax of jQuery and go directly to learn vue

js=long legs, jQuery=bicycle, vue=electric car
As long as the legs are long, you can ride an electric car instead of learning to ride a bicycle!

Summarize

From this point of view, the use of ajax is to bind some buttons or various other objects in JS, call the callback function when triggered, and perform data interaction from the interface to realize the dynamic interaction of data.

Guess you like

Origin blog.csdn.net/Tommy__li/article/details/127773864