封裝一個方法獲取url上面的參數

1、取參  
function getAllUrlParams( url) {
var queryString = url ? url. split( '?')[ 1] : window. location. search. slice( 1);
var obj = {};
if ( queryString) {
queryString = queryString. split( '#')[ 0];
var arr = queryString. split( '&');
for ( var i = 0; i < arr. length; i++) {
var a = arr[ i]. split( '=');
var paramNum = undefined;
var paramName = a[ 0]. replace( / \[ \d *\] /, function ( v) {
paramNum = v. slice( 1, - 1);
return '';
});
// 設置參數值(若是爲空則設置爲true)
var paramValue = typeof ( a[ 1]) === 'undefined' ? true : a[ 1];
// paramName = paramName.toLowerCase();
// paramValue = paramValue.toLowerCase();
if ( obj[ paramName]) {
if ( typeof obj[ paramName] === 'string') {
obj[ paramName] = [ obj[ paramName]];
}
if ( typeof paramNum === 'undefined') {
obj[ paramName]. push( paramValue);
} else {
obj[ paramName][ paramNum] = paramValue;
}
} else {
obj[ paramName] = paramValue;
}
}
}
return obj;
}
console. log( getAllUrlParams( 'http://display.intdmp.com/site_login_ijf.htm?app_key=adhu3e534be06456426b&acc=asda'));
//{app_key: "adhu3e534be06456426b", acc: "asda"}
 

2、存參數組

 pastingapp

function toQueryPair( key, value, bo) {
if ( typeof value === 'undefined') {
return key;
}
return key + '=' + ( bo ? encodeURIComponent( value === null ? '' : String( value)) : value === null ? '' : String(
value));
}
const toBodyString = function ( obj, bo = true) {
let ret = [];
for ( let key in obj) {
let values = obj[ key];
if ( values && values. constructor === Array) { //數組
let queryValues = [];
for ( let i = 0, len = values. length, value; i < len; i++) {
value = values[ i];
queryValues. push( toQueryPair( key, value));
}
ret = ret. concat( queryValues);
} else { //字符串
ret. push( toQueryPair( key, values, bo));
}
}
return ret. join( '&');
}
console. log( toBodyString({
a: 123546,
b: 'fdfdfd',
c: '9999'
})); //a=123546&b=fdfdfd&c=9999
相關文章
相關標籤/搜索