Adding a parameter to the URL with JavaScript

后端 未结 30 2570
刺人心
刺人心 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 07:51

    I like the answer of Mehmet Fatih Yıldız even he did not answer the whole question.

    In the same line as his answer, I use this code:

    "Its doesn't control parameter existence, and it doesn't change existing value. It adds your parameter to the end"

      /** add a parameter at the end of the URL. Manage '?'/'&', but not the existing parameters.
       *  does escape the value (but not the key)
       */
      function addParameterToURL(_url,_key,_value){
          var param = _key+'='+escape(_value);
    
          var sep = '&';
          if (_url.indexOf('?') < 0) {
            sep = '?';
          } else {
            var lastChar=_url.slice(-1);
            if (lastChar == '&') sep='';
            if (lastChar == '?') sep='';
          }
          _url += sep + param;
    
          return _url;
      }
    

    and the tester:

      /*
      function addParameterToURL_TESTER_sub(_url,key,value){
        //log(_url);
        log(addParameterToURL(_url,key,value));
      }
    
      function addParameterToURL_TESTER(){
        log('-------------------');
        var _url ='www.google.com';
        addParameterToURL_TESTER_sub(_url,'key','value');
        addParameterToURL_TESTER_sub(_url,'key','Text Value');
        _url ='www.google.com?';
        addParameterToURL_TESTER_sub(_url,'key','value');
        _url ='www.google.com?A=B';
        addParameterToURL_TESTER_sub(_url,'key','value');
        _url ='www.google.com?A=B&';
        addParameterToURL_TESTER_sub(_url,'key','value');
        _url ='www.google.com?A=1&B=2';
        addParameterToURL_TESTER_sub(_url,'key','value');
    
      }//*/
    

提交回复
热议问题