Adding a parameter to the URL with JavaScript

后端 未结 30 2599
刺人心
刺人心 2020-11-22 07:33

In a web application that makes use of AJAX calls, I need to submit a request but add a parameter to the end of the URL, for example:

Original URL:

30条回答
  •  误落风尘
    2020-11-22 08:07

    Try
    The regular expressions, so slow, thus:

    var SetParamUrl = function(_k, _v) {// replace and add new parameters
    
        let arrParams = window.location.search !== '' ? decodeURIComponent(window.location.search.substr(1)).split('&').map(_v => _v.split('=')) : Array();
        let index = arrParams.findIndex((_v) => _v[0] === _k); 
        index = index !== -1 ? index : arrParams.length;
        _v === null ? arrParams = arrParams.filter((_v, _i) => _i != index) : arrParams[index] = [_k, _v];
        let _search = encodeURIComponent(arrParams.map(_v => _v.join('=')).join('&'));
    
        let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + (arrParams.length > 0 ? '?' +  _search : ''); 
    
        // window.location = newurl; //reload 
    
        if (history.pushState) { // without reload  
            window.history.pushState({path:newurl}, null, newurl);
        }
    
    };
    
    var GetParamUrl = function(_k) {// get parameter by key
    
        let sPageURL = decodeURIComponent(window.location.search.substr(1)),
            sURLVariables = sPageURL.split('&').map(_v => _v.split('='));
        let _result = sURLVariables.find(_v => _v[0] === _k);
        return _result[1];
    
    };
    

    Example:

            // https://some.com/some_path
            GetParamUrl('cat');//undefined
            SetParamUrl('cat', "strData");// https://some.com/some_path?cat=strData
            GetParamUrl('cat');//strData
            SetParamUrl('sotr', "strDataSort");// https://some.com/some_path?cat=strData&sotr=strDataSort
            GetParamUrl('sotr');//strDataSort
            SetParamUrl('cat', "strDataTwo");// https://some.com/some_path?cat=strDataTwo&sotr=strDataSort
            GetParamUrl('cat');//strDataTwo
            //remove param
            SetParamUrl('cat', null);// https://some.com/some_path?sotr=strDataSort
    

提交回复
热议问题