How to use jquery to manipulate the querystring

后端 未结 6 2105
别跟我提以往
别跟我提以往 2021-02-08 22:36

I have a select dropdown with id\'s mapped to values. On the onChange event I want to redirect to the same url but with \'id=value\' appended to the querystring.

How do

6条回答
  •  温柔的废话
    2021-02-08 23:18

    Based on CoffeeMonster's answer:

    There is a problem when the location.href contains a hash part:

    www.example.com#hash becomes www.example.com#hash?id=whatever which results in ?id=whatever not being interpreted by the server.

    Fixed it by removing the hash part of the url: url.split("#")[0];

    // put function into jQuery namespace
    jQuery.redirect = function(url, params) {
    
        url = url || window.location.href || '';
        url = url.split("#")[0];
        url =  url.match(/\?/) ? url : url + '?';
    
        for ( var key in params ) {
            var re = RegExp( ';?' + key + '=?[^&;]*', 'g' );
            url = url.replace( re, '');
            url += ';' + key + '=' + params[key]; 
        }  
        // cleanup url 
        url = url.replace(/[;&]$/, '');
        url = url.replace(/\?[;&]/, '?'); 
        url = url.replace(/[;&]{2}/g, ';');
        // $(location).attr('href', url);
        window.location.replace( url ); 
    };
    

    Now www.example.com#hash becomes www.example.com?id=whatever

提交回复
热议问题