Set URL parameters without causing page refresh

后端 未结 3 1459
攒了一身酷
攒了一身酷 2021-02-20 16:06

How can you set URL parameters using History.pushState() to avoid browser refreshes? If there is a not a simple JS solution, is there already a popular library or b

3条回答
  •  遇见更好的自我
    2021-02-20 16:17

    Here is a simple function I wrote it isn't as neat as the above answer but it does the trick...

                function changeUrlParam (param, value) {
                    var currentURL = window.location.href;
                    var urlObject = currentURL.split('?');
                    var newQueryString = '?';
    
                    value = encodeURIComponent(value);
    
                    if(urlObject.length > 1){
                        var queries = urlObject[1].split('&');
    
                        var updatedExistingParam = false;
                        for (i = 0; i < queries.length; i++){
                            var queryItem = queries[i].split('=');
    
                            if(queryItem.length > 1){
                                 if(queryItem[0] == param){
                                    newQueryString += queryItem[0] + '=' + value + '&';
                                    updatedExistingParam = true;
                                 }else{
                                    newQueryString += queryItem[0] + '=' + queryItem[1] + '&';
                                 }
                            }
                        }
                        if(!updatedExistingParam){
                            newQueryString += param + '=' + value + '&';
                        }
                    }else{
                        newQueryString += param + '=' + value + '&';
                    }
                    window.history.replaceState('', '', urlObject[0] + newQueryString.slice(0, -1));
                }
    

提交回复
热议问题