This article mainly shares with you the detailed introduction of ajax simple encapsulation, hoping to help everyone.
ajax is generally divided into four simple parts:
Create an ajax object (if it is compatible with IE, you need to do some processing)
Connection, that is, the open method of the request object (get and post are slightly different, the get parameter must be placed after the url, and the request header must be set for post)
Send, that is, the send of the request object Function (the post parameter is placed in send)
is received and processed in the onreadystatechange (storage function or function name. Whenever the readyState attribute changes, the function will be called.) function .
You can also add timeouts.
You must first determine the status of readyState (there are four states)
①: 0, the request is not initialized;
②: 1, the server connection has been established;
③: 2, the request has been received;
④ : 3. The request is being processed;
⑤: 4. The request has been completed and the response is ready
When readyState is equal to 4, you have to judge the status of status
When the request is successful, the status status is 200-302, and there is 304 (caching)
'use strict'; var $ = {}; $.ajax = ajax; function ajax(options) { // 解析参数 options = options || {}; if (!options.url) return; options.type = options.type || 'get'; options.timeout = options.timeout || 0; // 1 创建ajax if (window.XMLHttpRequest) { // 高级浏览器和ie7以上 var xhr = new XMLHttpRequest(); } else { //ie6,7,8 var xhr = new ActiveXObject("Microsoft.XMLHTTP"); } // 2 连接 var str = jsonToUrl(options.data); if (options.type === 'get') { xhr.open('get', `${options.url}?${str}`, true); // 3 发送 xhr.send(); } else { xhr.open('post', options.url, true); // 请求头 xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); // 3 发送 xhr.send(); } // 接收 xhr.onreadystatechange = function() { // 完成 if (xhr.readyState === 4) { // 清除定时器 clearTimeout(timer); if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) { // 成功 options.success && options.success(xhr.responseText); } else { options.error && options.error( xhr.status ); } } }; // 超时 if (options.timeout) { var timer = setTimeout(function(){ alert("超时了"); xhr.abort(); // 终止 },options.timeout); } } // json转url function jsonToUrl(json) { var arr = []; json.t = Math.random(); for(var name in json) { arr.push(name + '=' + encodeURIComponent(json[name])); } return arr.join('&'); }
Related recommendations:
WeChat applet implements a code example of simple encapsulation of network requests
php simply encapsulates some common JS operations_PHP tutorial
The above is the detailed content of Detailed introduction to ajax simple packaging. For more information, please follow other related articles on the PHP Chinese website!