通用JS工具類封裝——網路資料請求功能、獲取服務端介面 url、引數功能
阿新 • • 發佈:2018-11-23
程式碼片段
'use strict';
var conf = {
serverHost = ''
};
var _mm = {
//網路請求功能
request : function(param){
var _this = this;
$.ajax({
type : param.method || 'get',
url : param.url || '',
dataType : param.type || 'json',
data : param.data || '' ,
success : function(res){
//請求成功
if(0 === res.status){
typeof param.success === 'function' && param.success(res.data, res.msg);
}
//請求資料錯誤
else if(1 === res.status){
typeof param.error === 'function' && param.error(res.message);
}
},
error : function(err){
typeof param.error === 'function' && param.error(res.statusText);
}
});
},
//獲取伺服器地址
getServerUrl : function(path) {
return conf.serverHost + path;
},
//獲取 url 引數
getUrlParam : function(name){
var reg = new RegExp('(^|&)'+ name + '=([^&]*)(&|$)');
var result = window.location.search.substr(1).match(reg);
return result ? decodeURIComponent(result[2]) : null;
}
};
module.exports = _mm;
解釋
a.typeof
:操作符返回一個字串,指示未經計算的運算元的型別。
b.var reg = new RegExp('(^|&)'+ name + '=([^&]*)(&|$)')
:正則表示式子。
c.window.location.search.substr(1).match(reg)
:
window.location.search
:返回從問號到URL末尾的所有內容(?q=javascript);substr(1)
:返回一個從指定位置開始的指定長度的子字串(這裡設定為1,是為了把url中的?號去掉);match(reg)
:根據正則表示式匹配需要的資料。