Adding a parameter to the URL with JavaScript

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

    I have a 'class' that does this and here it is:

    function QS(){
        this.qs = {};
        var s = location.search.replace( /^\?|#.*$/g, '' );
        if( s ) {
            var qsParts = s.split('&');
            var i, nv;
            for (i = 0; i < qsParts.length; i++) {
                nv = qsParts[i].split('=');
                this.qs[nv[0]] = nv[1];
            }
        }
    }
    
    QS.prototype.add = function( name, value ) {
        if( arguments.length == 1 && arguments[0].constructor == Object ) {
            this.addMany( arguments[0] );
            return;
        }
        this.qs[name] = value;
    }
    
    QS.prototype.addMany = function( newValues ) {
        for( nv in newValues ) {
            this.qs[nv] = newValues[nv];
        }
    }
    
    QS.prototype.remove = function( name ) {
        if( arguments.length == 1 && arguments[0].constructor == Array ) {
            this.removeMany( arguments[0] );
            return;
        }
        delete this.qs[name];
    }
    
    QS.prototype.removeMany = function( deleteNames ) {
        var i;
        for( i = 0; i < deleteNames.length; i++ ) {
            delete this.qs[deleteNames[i]];
        }
    }
    
    QS.prototype.getQueryString = function() {
        var nv, q = [];
        for( nv in this.qs ) {
            q[q.length] = nv+'='+this.qs[nv];
        }
        return q.join( '&' );
    }
    
    QS.prototype.toString = QS.prototype.getQueryString;
    
    //examples
    //instantiation
    var qs = new QS;
    alert( qs );
    
    //add a sinle name/value
    qs.add( 'new', 'true' );
    alert( qs );
    
    //add multiple key/values
    qs.add( { x: 'X', y: 'Y' } );
    alert( qs );
    
    //remove single key
    qs.remove( 'new' )
    alert( qs );
    
    //remove multiple keys
    qs.remove( ['x', 'bogus'] )
    alert( qs );
    

    I have overridden the toString method so there is no need to call QS::getQueryString, you can use QS::toString or, as I have done in the examples just rely on the object being coerced into a string.

提交回复
热议问题