Summary of Ajax and Axios related interview questions

Ajax and Axios

AJAX: The client can send a request to the server by 'knocking', and realize partial update of the page when the page is not refreshed.
Function: what is sent is the http request, and the corresponding data is requested

Axios: It is a promise-based network request library that works in node.js and browsers. It is isomorphic (that is, the same set of code can run in browsers and node.js). On the server side it uses the native node.js http module, while on the client side (browser side) it uses XMLHttpRequest.

1. Synchronous request and asynchronous request

  • Synchronization: Submit the request -> wait for the server to process -> return after the process is completed and the client browser cannot do anything during this period
  • Asynchronous: The request is triggered by an event -> server processing (this is the browser can still do other things) -> processing is completed

2. Ajax usage of fetch, axios, jquery

are used for http requests

Relationship diagram:
Xhr (code complex rang) -> $ajax encapsulated by jquery -> fetch (new technology) axios (encapsulates ajax Xhr)

What is the small extended JSONg format?

  • is a file transfer format
  • Multiple key-value pairs in the form
  • The way to get the attribute a in the JSON object obj
  • obj.a
  • obj['a'] (array method)

$ajax encapsulated by jquery

The format of the request is the form format by default

    $.ajax({
    
    
    //扩展方法,设置请求方法
    methods:"POST"
    //请求的参数  (1.post默认表单格式的提交,2.get:queryString)
    //3.json格式请求
    header:{
    
    'Content-type':'application/json'}
    //请求参数
    data:JSON.stringfy({
    
    a:10})
    //请求地址
    url(http://localhost:99),
    //拿到调用的数据
    success:function(data){
    
    
    conssole.log(data)
    }
    })
    

fetch

Now the browser comes with it, no need to download any js package

    //返回的是promise
    fetch("http:/localhost:99?b=2"{
    
    
   //加入指定参数
   method:"POST"
   //以表单的形式提交
   //也可以JSON方式提交
   header:{
    
    "content-type":"application/x-www-form-urlencoded"}
   //请求参数
   body:"a=12&b=33"
   }).then(response=>response.json()).then(data=>console.log(data)

axios

Not only can HTTP requests be made on the front end, but also http requests can be made on the back end.
The format of the request is JSON by default.

    axios({
    
    
    url:"http://localhost:99?b=2",
    method:"POST",
    //支持表单的格式提交
     header:{
    
    "content-type":"application/x-www-form-urlencoded"}
     data:"a=123&b=156"
     data:{
    
    a:12} 
    //then方法 拿到调用的数据
    }).then(res=>console.log(res.data))

3. JS cross-domain resource sharing (CORS problem)

Cross-domain : Refers to the fact that the browser cannot execute scripts from other websites. It is caused by the browser's same-origin policy , which is a security restriction imposed by the browser.

What is the same-origin policy?

  • It is a convention, which is the core and most basic security function of the browser. If the same-origin policy is missing, the normal functions of the browser may be affected. It can be said that the Web is built on the basis of the same-origin policy, and the browser is only an implementation of the same-origin policy. Generally speaking, the three elements of the request must be the same, (protocol, domain name, port) are the same,

How to solve cross domain?
Commonly used three

  • 1.
    The principle of jsonp is that js scripts or CSS files, video images and pictures requested through href or src do not have cross-domain problems. As long as AJAX requests data, there will be cross-domain problems, but Jsonp has flaws and can only request get
    原理是通过href或者src请求下来的js脚本或者CSS文件视频图片都是不存在跨域问题,只要AJAX请求数据才存在跨域问题,但是Jsonp有瑕疵只能请求get
    前端:
    function f(data){
    
    
    alter(data)
    }
    <script src="请求地址URL?callback=f"></script>
    
    后端:
    var funcname = request.query.callback
    response.send(funcname+"('你好')"
    //f('你好')
  • 2. cors request set
    CORS: a W3C standard, it requires the support of both the browser and the server, and the browser basically supports it. Therefore, if you want to realize CORS communication, as long as the server implements the CORS interface, it can work. Principle: It uses
    additional HTTP header to tell the browser that web applications running on one origin(domain) are allowed to access specified resources from different origin servers. A resource initiates a cross-origin HTTP request when a resource is requested from a different domain, protocol, or port than the server on which the resource itself resides. And CORS allows browsers to send cross-domain requests to cross-origin servers, thus overcoming Ainsert image description here
  • 3. Proxy forwarding
    • Backend setting proxy and allowing cross-domain requests
  • vue-cli configuration request proxy

What is a proxy?

  • Conventional: A client requests to B server
  • Becomes: Proxy server C receives A's request. C server requests B server to return to A client (the server request server does not exist across domains)

4. Ajax solves the browser cache problem

  • Add anyAjaxObj.setRequestHeader("If-Modified-Since", "0") before sending ajax request.
  • Add anyAjaxObj.setRequestHeader("Cache-Control", "no-cache") before sending ajax request.
  • Add a random number after the URL: "fresh=" + Math.random().
  • Add the time after the URL: "nowtime=" + new Date().getTime().

5. The status returned by ajax

0 - (uninitialized) the send() method has not been called
1 - (loading) the send() method has been called and the request is being sent
2 - (loading complete) the send() method has been executed and all response content has been received
3 - (Interactive) Parsing the response content
4 - (Complete) The response content has been parsed and can be called on the client

6. Implement an Ajax

AJAX creates an asynchronous object XMLHttpRequest and operates the XMLHttpRequest object
(1) Set request parameters (request method, relative path of the requested page, whether asynchronous or not) (
2) Set a callback function, a function that processes server responses, using onreadystatechange, similar to function
pointers
(3) Get the readyState attribute of the asynchronous object: this attribute stores the status information of the server response. Whenever
the readyState changes, the onreadystatechange function will be executed.
(4) Determine the status of the response message. If it is 200, it means that the server is running normally and returns the response data.
(5) To read the response data, the data returned by the server can be retrieved through the responseText attribute.

7. How to implement ajax request, if I have multiple requests, I need to execute these ajax requests in a certain order at one time, is there any way?

使 ajax 请求按照队列顺序执行,通过调用递归函数:
//按顺序执行多个 ajax 命令,因为数量不定,所以采用递归

function send(action, arg2) {
    
    

想要获取更多前端开发相关学习资料,请加微信1124692领取>>>>>>
//将多个命令按顺序封装成数组对象,递归执行
//利用了 deferred 对象控制回调函数的特点
$.when(send_action(action[0], arg2))
.done(function () {
    
    
//前一个 ajax 回调函数完毕之后判断队列长度
if (action.length > 1) {
    
    
//队列长度大于 1,则弹出第一个,继续递归执行该队列
action.shift();
send(action, arg2);
}
}).fail(function (){
    
    
//队列中元素请求失败后的逻辑
//
//重试发送
//send(action, arg2);
//
//忽略错误进行下个
//if (action.length > 1) {
    
    
//队列长度大于 1,则弹出第一个,继续递归执行该队列
// action.shift();
// send(action, arg2);
//}
});
}
//处理每个命令的 ajax 请求以及回调函数
function send_action(command, arg2) {
    
    
var dtd = $.Deferred();//定义 deferred 对象
$.post( "url", {
    
    
command: command, 
想要获取更多前端开发相关学习资料,请加微信1124692领取>>>>>>
arg2: arg2
}
).done(function (json) {
    
    
json = $.parseJSON(json);
//每次请求回调函数的处理逻辑
//
//
//
//逻辑结束
dtd.resolve();
}).fail(function (){
    
    
//ajax 请求失败的逻辑
dtd.reject();
});
return dtd.promise();//返回 Deferred 对象的 promise,防止在外部

8. Handwritten native Ajax

var xhr = new XMLHttpRequest();
xhr.open('get', 'aabb.php', true);
xhr.send(null);
xhr.onreadystatechange = function() {
    
    
if(xhr.readyState==4) {
    
    
if(xhr.status==200) {
    
    
console.log(xhr.responseText);
}
}
} 

9. What are the advantages and disadvantages of Fetch and Ajax?

Promise is convenient and asynchronous, and it is easier to write than native ajax when you don't want to use jQuery.

The editor has sorted out these at present, and will update them in the future~ You can learn and summarize together
insert image description here

Guess you like

Origin blog.csdn.net/qq_59079803/article/details/124107142
Recommended