How to encode a query string so that it is the value of another query string in javascript?

后端 未结 4 915
我在风中等你
我在风中等你 2020-12-28 13:15

I have a javascript function which passes as a query string value another query string.

In other words, I want the query string to be:

http://www.so         


        
相关标签:
4条回答
  • 2020-12-28 13:17
    function downloadFile(){
          var filePath = "C:/Users/HP/Desktop/Project Folder/DemoProject/";
    
          var fileInfo = "Error_Issue Minor Cosmetic & Major Fatal Issues (Demo_Project) (2017)_GeneratedOn_12_21_2017 21924 AM.xlsx";
          if((filePath != undefined && filePath.length > 0) && (fileName != undefined && fileName.length > 0)){
            var downloadUrl = "../download?fileName="+encodeURIComponent(fileName)+"&filePath="+encodeURIComponent(filePath);
            $window.location = downloadUrl;
          }else{
            alert("Please define a fileName for downloading...");
          }
    }
    
    0 讨论(0)
  • 2020-12-28 13:21
    javascript:alert(escape('?key=value1&key2=value2'));
    

    Works fine for me?

    0 讨论(0)
  • 2020-12-28 13:27

    encodeURIComponent will work. (You may or may not want the leading ‘?’, depending on what the script is expecting.)

    var c= 'd e'
    var query= '?a=b&c='+encodeURIComponent(c);
    var uri= 'http://www.example.com/script?query='+encodeURIComponent(query);
    window.location= uri;
    

    Takes me to:

    http://www.example.com/script?query=%3Fa%3Db%26c%3Dd%2520e

    When you hover over that it may appear once-decoded in the browser's status bar, but you will end up in the right place.

    escape/unescape() is the wrong thing for encoding query parameters, it gets Unicode characters and pluses wrong. There is almost never a case where escape() is what you really need.

    0 讨论(0)
  • 2020-12-28 13:29

    Native escape method does that. but also you can create a custom encoder like:

    function encodeUriSegment(val) {
      return encodeUriQuery(val, true).
                 replace(/%26/gi, '&').
                 replace(/%3D/gi, '=').
                 replace(/%2B/gi, '+');
    }
    

    this will replace keys used in query strings. further more you can apply it to any other custom encodings by adding needed key-values pairs.

    0 讨论(0)
提交回复
热议问题