How to pass % in a URL query string?

2020-07-05 06:52发布

I am trying to pass a string via HTTP request which has one of the character as % in the URL query string.

url = url + "?q=" + str + "&block=" + block;  // str contains the '%' character

But on the ColdFusion page where I'm sending this information is returning following error:

Element Q is undefined in URL.

How can I encode the % sign in a URL?

标签: javascript
5条回答
别忘想泡老子
2楼-- · 2020-07-05 07:33

We can use URLEncodedFormat() in ColdFusion as well as we can use the below mentioned one.

  • encodeURI(...)
  • encodeURIComponent

This two also help us to resolve our issue.

查看更多
Rolldiameter
4楼-- · 2020-07-05 07:37

Pass your string trough the function encodeURI(...) it will escape all the special characters not only the %

查看更多
该账号已被封号
5楼-- · 2020-07-05 07:49

You should url-encode all the values you are passing as query parameters, but the url-encoding for % is %25

Update: if you're constructing the query parameters in javascript, you probably want to do:

url=url+"?q="+encodeURIComponent(str)+"&block="+encodeURIComponent(block)

(Updated again with ZeissS' very helpful suggestion to use encodeURIComponent instead of escape. See also http://xkr.us/articles/javascript/encode-compare/)

查看更多
女痞
6楼-- · 2020-07-05 07:51
登录 后发表回答