如何对一个查询字符串进行编码,以便它是JavaScript中另一个查询字符串的值? [英] How to encode a query string so that it is the value of another query string in javascript?

查看:132
本文介绍了如何对一个查询字符串进行编码,以便它是JavaScript中另一个查询字符串的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



换句话说,我希望查询字符串是:

  http://www.somesite.com/?somequery=%3fkey%3dvalue1%2520%26%2520key2%3value3 

但是,如果我重定向如下:

  var url ='http://www.somesite.com/?somequery='; 
url + = escape('?key = value1& key2 = value2');
window.location = url;

最终为 http://www.somesite.com?somequery =?key1 = value1& key2 = value2 在firefox和IE7这意味着我无法正确解析查询字符串。



我也尝试使用encodeURIComponent,它不起作用。



是否有另一个功能或黑客强制重定向来保持 somequery 值转义?

解决方案

encodeURIComponent将工作。 (你可能也可能不想要领导'?',取决于脚本的期望。)

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

请访问:


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


当你悬停在它可能会出现在浏览器的状态栏中一次解码,但是你最终会在正确的位置。



escape / unescape()是编码查询参数的错误的东西,它得到Unicode字符和错误。几乎没有一种情况,escape()是你真正需要的。


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.somesite.com/?somequery=%3fkey%3dvalue1%2520%26%2520key2%3value3

However, if I redirect like this:

var url = 'http://www.somesite.com/?somequery=';
url += escape('?key=value1&key2=value2');
window.location = url;

it ends up as http://www.somesite.com?somequery=?key1=value1&key2=value2 in firefox and IE7 which means that I can't parse the query string correctly.

I also tried using encodeURIComponent which didn't work either.

Is there another function or a hack to force the redirect to keep the somequery value escaped??

解决方案

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.

这篇关于如何对一个查询字符串进行编码,以便它是JavaScript中另一个查询字符串的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆