Adding a parameter to the URL with JavaScript

后端 未结 30 2242
刺人心
刺人心 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:09

    If you're messing around with urls in links or somewhere else, you may have to take the hash into account as well. Here's a fairly simple to understand solution. Probably not the FASTEST since it uses a regex... but in 99.999% of cases, the difference really doesn't matter!

    function addQueryParam( url, key, val ){
        var parts = url.match(/([^?#]+)(\?[^#]*)?(\#.*)?/);
        var url = parts[1];
        var qs = parts[2] || '';
        var hash = parts[3] || '';
    
        if ( !qs ) {
            return url + '?' + key + '=' + encodeURIComponent( val ) + hash;
        } else {
            var qs_parts = qs.substr(1).split("&");
            var i;
            for (i=0;i

提交回复
热议问题