How can I include special characters in query strings?

后端 未结 7 1003
日久生厌
日久生厌 2020-12-09 15:22

URL http://localhost/mysite/mypage?param=123 works fine. However, if I want to put some special characters in param, like ?, /

7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 15:51

    You need to encode the query parameters before combining them to form a url. The function needed here is encodeURIComponent.For example,

    the url you need to create is:

    http://localhost/mysite/mypage?param=a=?&b=/
    

    Now, assuming that ? and / comes as variables, you need to encode them before putting in the url. So lets create your url using this function(I am expecting two query parameters):

     var q1 = "a=?"; //came from some input or something
        var q2 = "/"; //came from somewhere else
    
        var faultyUrl =  "http://localhost/mysite/mypage?param="+ q1 +"&b=" + q2; 
    // "http://localhost/mysite/mypage?param=a=?&b=/"
    
    
        var properUrl =  "http://localhost/mysite/mypage?param="+ encodeURIComponent(q1) +"&b=" + encodeURIComponent(q2); 
    //"http://localhost/mysite/mypage?param=a%3D%3F&b=%2F"
    

    This function is in basic JS and supported in all the browsers.

提交回复
热议问题