How to include special characters in query strings

有些话、适合烂在心里 提交于 2019-12-03 09:41:06

You have to encode special characters in URLs. See: http://www.w3schools.com/tags/ref_urlencode.asp

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.

In JavaScript you can use the encodeURI() function.

ASP has the Server.URLEncode() function.

HttpServerUtility.UrlEncode in .NET

Easy way to pass QueryString value with special character using javascript:

var newURL=encodeURIComponent(uri);
window.location="/abc/abc?q="+newURL;

You need to use encode special characters, see this page for a reference.

If you're using PHP, there's a function to do this, called urlencode().

You need to substitute the characters with URL entities. Some information here.

I did below, it works fine.

const myQueryParamValue = "You&Me";
const ajaxUrl = "www.example.com/api?searchText="+encodeURIComponent(myQueryParamValue)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!