当前位置:网站首页>JS small method
JS small method
2022-07-28 23:24:00 【Corner sheep】
(function () {
// Remove the spaces at the left and right ends of the string
String.prototype.trim = function () {
return this.replace(/(^\s*)|(\s*$)/g, "");
};
// // Remove the space on the left
String.prototype.ltrim = function () {
return this.replace(/(^\s*)/g, "");
};
// Remove the space on the right
String.prototype.rtrim = function () {
return this.replace(/(\s*$)/g, "");
};
// It can be written as a function like this :(trim(str))
function trim(str) {
// Delete the left and right spaces
return str.replace(/(^\s*)|(\s*$)/g, "");
}
function ltrim(str) {
// Remove the space on the left
return str.replace(/(^\s*)/g, "");
}
function rtrim(str) {
// Remove the space on the right
return str.replace(/(\s*$)/g, "");
}
})();
// ajax Encapsulation
function createXhr() {
if (typeof XMLHttpRequest != undefined) {
return new XMLHttpRequest();
} else {
var xhr = null;
try {
xhr = new ActiveXObject("MSXML2.XmlHttp.6.0");
return xhr;
} catch (e) {
try {
xhr = new ActiveXObject("MSXML2.XmlHttp.3.0");
return xhr;
} catch (e) {
throw Error(" Your broken browser does not support ajax");
}
}
}
}
/*****************ajax ******************/
// The first method :ajax Encapsulation of functions
/** * ajax: async javascript and xml / json * Asynchronous JavaScript and xml / json {} * purpose : Data interaction ( Network request ) * XMLHTTPRequest() * * * Simple request ajax: * 1. Request mode : get / post / head * 2. Request header information : Can only contain : * Accept: * Accept-Encoding: gzip, deflate, br Accept-Language: zh-CN,zh;q=0.9 Connection: keep-alive Host: 127.0.0.1:5501 If-Modified-Since: Tue, 27 Aug 2019 11:48:43 GMT If-None-Match: W/"6f2-16cd2e81e70" Referer: http://127.0.0.1:5501/view/index.html Sec-Fetch-Mode: cors Sec-Fetch-Site: same-origin User-Agent: Content-Type: application/x-www-form-urlencode ; multipart/form-data; text/plain; * * method: Request mode get * url: Requested address * callback: Callback function success: Successful callback function * data: Request data ( Request parameters ) * falg: Asynchronous or not * isAsync: Asynchronous or not true * * headers : {} * @param { Object } options * */
function ajax(options) {
// var xhr = new XMLHttpRequest();
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} else {
return alert(" The current browser does not support XMLHTTPRequest");
}
var method = "";
var data = "";
var isAsync = typeof options.isAsync === "undefined" ? true : options.isAsync;
var url = options.url;
var success =
typeof options.success === "function" ? options.success : function () {
};
if (options.method) {
method = options.method.toUpperCase();
} else {
method = "GET";
}
// 0 - 4
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
success(JSON.parse(xhr.responseText));
}
}
};
if (typeof options.data === "object") {
for (var prop in options.data) {
data += prop + "=" + options.data[prop] + "&";
}
data = data.slice(0, data.length - 1);
} else {
data = options.data;
}
if (options.method === "GET") {
xhr.open(method, url + "?" + data, isAsync);
xhr.send();
} else {
// Establishing a connection
xhr.open(method, url, isAsync);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencode");
// key=value&key1=value
// Sending data
xhr.send(data);
}
}
/****************************************/
// The second method :ajax Encapsulation of functions
function ajax(opts) {
var set = extend(
{
url: "",
data: "",
type: "GET",
timeout: 5000,
onbeforerequest: function () {
}, // Before sending the request
onsuccess: function () {
}, // Data accepted successfully
onnottmodified: function () {
}, // The data has not changed
onfailure: function () {
}, // request was aborted
},
opts || {
}
);
var xhr = createXhr();
if (set.type.toUpperCase() == "GET") {
// Decide whether to add cache ? Add one date character string , Prevent caching ( When there is a cache , The request is no longer sent to the backend , Read local directly )
if (set.data) {
set.url += (set.url.indexOf("?") >= 0 ? "&" : "?") + "t=" + +new Date();
}
}
// whenever readyState When the change , It will trigger onreadystatechange event
// State detection
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
// Callback function
set.onsuccess.call(xhr);
if (xhr.status >= 200 && hr.status < 300) {
} else if (xhr.status == 304) {
set.onnottmodified.call(xhr);
} else {
set.onfailure.call(xhr);
}
}
// Open the link
xhr.open(set.type, set.url);
if (set.type.toUpperCase() == "POST") {
xhr.setRequestHeader("content-Type", "application/x-www-form-urlencoded");
}
// This function will call back by itself , Usually this step is useless
set.onbeforerequest();
// Timeout reset time
if (set.timeout) {
setTimeout(function () {
xhr.onreadystatechange = function () {
};
xhr.abort();
set.onfailure();
}, set.timeout);
}
// This step is to send data , The back-end server will receive
xhr.send(set.data);
};
}
/****************************************/
边栏推荐
- Goer shares and Shanghai Taisi Weida growth cooperation agreement! Special SOC jointly promotes the development of TWS headphones
- High quality subroutine 3 - a good name
- Failure [INSTALL_FAILED_TEST_ONLY: installPackageLI]
- [image segmentation] vein segmentation based on directional valley detection with matlab code
- This year, MediaTek 5g chip shipments are expected to reach 50million sets!
- The industry's first cloud native security detection dual model! Safety dog heavyweight report appears at the digital China Construction Summit
- leetcode101. 对称二叉树
- Seagate released a new risc-v architecture processor: the performance of mechanical hard disk soared 3 times
- Pgbench benchmark PostgreSQL
- Xinhuazhang announced the completion of more than 200million a-round financing and the comprehensive layout of eda2.0 R & D
猜你喜欢

The functions and differences of display, visibility and overflow

After reading MySQL database advanced practice (SQL xiaoxuzhu)

业界首创云原生安全检测双模型!安全狗重磅报告亮相数字中国建设峰会

Thesis reading (3) - googlenet of classification
![[radar] radar signal online sorting based on kernel clustering with matlab code](/img/56/1f8e8690b47fc4a1f101d4e530b87f.png)
[radar] radar signal online sorting based on kernel clustering with matlab code

Sdwebimage source code combs 5 author motivation, modifies directory, and changes inheritance relationship

Xshell7, xftp7 personal free version official download, no need to crack, no activation, download and use

xshell7,xftp7个人免费版官方下载,无需破解,免激活,下载即可使用

这个胶水有多强呢?
![[physical application] atmospheric absorption loss with matlab code](/img/72/e6ac23012a59ac48a37bcbb068890b.png)
[physical application] atmospheric absorption loss with matlab code
随机推荐
Advanced C language: pointer (3)
[MySQL series] addition, deletion, modification and query of MySQL tables (Advanced)
Introduction to address book export without code development platform
Target detection notes -yolo
Text is hidden beyond and ellipsis is displayed
Performance optimized APK slimming
sql优化常用的几种方法
Typescript防止基类被实例化
The applet vant webapp component is missing, and the referenced component reports an error
Subscript in swift
18 diagrams, intuitive understanding of neural networks, manifolds and topologies
零念科技完成Pre-A轮融资,推动智能驾驶平台软件国产替代
Inheritance in swift
Servlet的使用手把手教学(一)
Binary search tree
pg_ Installation and use of RMAN "PostgreSQL"
当初的“你“为什么做测试/开发程序员?自己存在的价值......
RouterOS 有限dns劫持及check
MyCms 自媒体商城 v3.6 发布,兼容微擎应用开发(Laravel框架)
No code development platform address book tutorial