Ajax Interview Questions | Front End

The Ajax interview questions in this article are mainly derived from online articles and courses, and the source will be indicated.
This article is primarily a memo for personal use.
Notes on Ajax knowledge points


1. What is Ajax

1. The concept of Ajax

Ajax is asynchronous javascript and xml
Ajax is a technique for creating fast dynamic web pages

2. The role, advantages and disadvantages of Ajax

Role : ajax is used to interact with the background

Advantages :

  • The biggest advantage is that the page does not need to be refreshed, and communicates with the server within the page, which is a very good user experience.
  • Communicate with the server in an asynchronous manner, without interrupting operations.
  • The work previously burdened by the server can be transferred to the client, reducing the server and bandwidth, and minimizing redundant requests.
  • Based on standardized and widely supported technology, no plug-ins or applets need to be downloaded.

Disadvantages :

  • Ajax killed the Back and History functions, that is, the destruction of the browser mechanism. It is not possible to move forward and backward using the browser.
  • Security issues: cross-site scripting attacks, SQL injection attacks, etc.
  • The support for search engines is relatively weak. If not used properly, AJAX will increase the flow of network data, thereby reducing the performance of the entire system.

Question answer source

3. How many request methods does Ajax have? Their pros and cons?

Commonly used post, get, delete. Copy, head, link, etc. are not commonly used.

a. The difference in code
(1) get passes parameters through url
(2) post sets the request header to specify the request data type

b. Differences in use
(1) post is safer than get
(because the post parameters are in the request body. The get parameters are on the url)
(2) the transmission speed of get is faster than that of post, which is determined by passing parameters.
(Post passes parameters through the request body, and the background receives them through data streams. The speed is a little slower. And get can be directly obtained by passing parameters through url) (3) There is no
limit to the large theory of post transfer files, and the size of get transfer files is about 7-8k ie4k
( 4) get data post upload data
(uploaded data is more and the uploaded data is important data. Therefore, post is the best choice no matter in terms of security or data level)
source of question answer

4.json string conversion set json object, json object conversion json string

//字符串转对象
JSON.parse(json)
eval('(' + jsonstr + ')')   
// 对象转字符串
JSON.stringify(json)

Question answer source

5. How to cancel ajax request

(1) Native xhr cancel request

var xhr = new XMLHttpRequest();
xhr.abort();

(2) Axios cancels the request
(i) Create a cancel token using the CancelToken.source factory method

const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/123', {
    
    
    cancelToken: source.token
}).catch(function(thrown) {
    
    
    if (axios.isCancel(thrown)) {
    
    
        console.log('Request canceled', thrown.message);
    } else {
    
    
    // 处理错误
    }
});
axios.post('/user/123', {
    
    
    name: '小明'
}, {
    
    
    cancelToken: source.token
})
// 取消请求(message 参数是可选的)
source.cancel('canceled by the user.');

(ii) Pass an executor function to the constructor of CancelToken to create the cancel token

const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
    
    
  cancelToken: new CancelToken(function executor(c) {
    
    
    // executor 函数接收一个 cancel 函数作为参数
    cancel = c;
  })
});
// cancel the request
cancel();

Question answer source

6. What is the point of canceling the ajax request

The sent request may still reach the backend
(1) cancel the subsequent callback processing to avoid redundant callback processing, and in special cases, (2) send it first and then return, causing the data in the callback to be overwritten incorrectly
(3) cancel loading effect, and other interactive effects of the request, especially in single-page applications, after page A jumps to page B, the request of page A should be canceled, otherwise some processing in the callback may affect page B (4) timeout processing
, Error handling, etc. are omitted, saving resources

Question answer source


Two, cross-domain

1. What will cause cross-domain?

The same-origin policy is a browser security policy.
Same origin: The protocol, domain name, and port number must be exactly the same.
Violation of the same-origin policy is cross-domain.

2. What are the cross-domain solutions?

(1) JSONP
a. What is
JSONP (JSON with Padding), an unofficial cross-domain solution that only supports get requests .
b. Principle
Dynamically create a script tag. Using the src attribute of the script tag is not restricted by the same-origin policy. Because all src attributes and href attributes are not restricted by the same-origin policy. Third-party server data content may be requested.

c. steps

  • to create a script tag
  • The src attribute of the script sets the interface address
  • Interface parameters must have a custom function name, otherwise the background cannot return data.
  • Receive data returned by the background by defining the function name
//去创建一个script标签
var  script = document.createElement("script");
//script的src属性设置接口地址 并带一个callback回调函数名称
script.src = "http://127.0.0.1:8888/index.php?callback=jsonpCallback";
//插入到页面
document.head.appendChild(script);
//通过定义函数名去接收后台返回数据
function jsonpCallback(data){
    
    
    //注意  jsonp返回的数据是json对象可以直接使用
    //ajax  取得数据是json字符串需要转换成json对象才可以使用。
}

(2) CORS
a. What is
CORS (Cross-Origin Resource Sharing), cross-domain resource sharing, CORS is the official cross-domain solution.
Features:
There is no need to do any special operations on the client side, and it is completely processed in the server. It supports get and post requests. A new set of HTTP header fields has been added to the cross-domain resource sharing standard, allowing the server to declare which source sites are available through the browser. Which resources the permissions access.
b. Principle
After the server sets the Access-Control-Allow-Origin HTTP response header, the browser will allow cross-domain requests

c. steps

//需要后台设置
Access-Control-Allow-Origin: *              //允许所有域名访问,或者
Access-Control-Allow-Origin: http://a.com   //只允许所有域名访问

Supplement:
(3) Set document.domain
a. Principle
For pages under the same main domain name and different subdomain names, you can set document.domain to make them the same domain
b. Limit
the interoperability between pages provided by the same domain document, which needs to be loaded into iframe Page
c. Steps

// URL http://a.com/foo
var ifr = document.createElement('iframe');
ifr.src = 'http://b.a.com/bar'; 
ifr.onload = function(){
    
    
    var ifrdoc = ifr.contentDocument || ifr.contentWindow.document;
    ifrdoc.getElementsById("foo").innerHTML);
};

ifr.style.display = 'none';
document.body.appendChild(ifr);

(4) Use Apache as forwarding (reverse proxy) to make cross-domain become same-domain

Question answer source


3. Comparative questions

1. What is the difference between Ajax, Fetch, and Axios?

  • ajax is a term for js asynchronous technology, and the related api is xhr, which is a term
  • fetch is a new standard api for network requests added by es6, it is an api
  • axios is a third-party library for network requests, it is a library

Question answer source


4. Handwritten questions

1. Handwritten Ajax original request

//1.创建 XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
//2.规定请求的类型、URL 以及是否异步处理请求。
xhr.open('GET',url,true);
//3.发送信息至服务器时内容编码类型
//设置响应头
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
//4.发送请求
xhr.send(null);  
//5.接受服务器响应数据
xhr.onreadystatechange = function () {
    
    
    if(xhr.readyState ===4){
    
    
    //判断响应状态码  200 404 403 401 500
    //2xx 成功
      if(xhr.status >= 200 && xhr.status < 300){
    
    
      
      }else{
    
    
     
      }
   }
}

Question answer source link

Guess you like

Origin blog.csdn.net/qq_42376600/article/details/128064436