JavaScript window.location 行为
使用以下代码,我将用户重定向到 php 脚本,在其中执行一些操作:
requestObject.queries = {
lv : searchQueryLV,
desc : searchQueryDesc,
ru : searchQueryRU,
oth : searchQueryOth
};
var queryStr = $.param(requestObject);
location.replace('http://' + location.host + '/path/to/file.php?' + queryStr);
问题是 queryStr 可能包含一些 html 特殊字符,如标签等。
当它包含它们时,我的代码会失败。它以搜索部分如下所示的 URL 结尾:
queryType=search&queries[lv]=<br>&queries[desc]=&queries[ru]=&queries[oth]=
我无法获取,如您所见,我对查询字符串进行编码:
$.param(requestObject);
当我 console.log 时,它会按必须显示。但是当我将它传递给 location.replace() 时,情况就变得一团糟。我尝试过使用 JS 本机encodeURI 手动构建它,但这没有帮助。
如果你能帮助我,我会很高兴。
With the following code I am redirecting user to a php script, where some actions are performed:
requestObject.queries = {
lv : searchQueryLV,
desc : searchQueryDesc,
ru : searchQueryRU,
oth : searchQueryOth
};
var queryStr = $.param(requestObject);
location.replace('http://' + location.host + '/path/to/file.php?' + queryStr);
The problem is that the queryStr may contains some html special chars, like tags etc.
And when it contains them, my code fails. It ends up with the URL where the search part looks like that:
queryType=search&queries[lv]=<br>&queries[desc]=&queries[ru]=&queries[oth]=
I can't get, as you can see, I encode the queryString:
$.param(requestObject);
And when I console.log it, it is displayed as it must. But when I pass it to location.replace() it's a mess. I've tried building it manually, using JS native encodeURI, but that doesn't help.
I would be glad if you could help me with that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是一个 jquery URLEncode/Decode 插件:(我在自己的项目中使用它)
Here is a jquery URLEncode/Decode Plugin: (i use it in my own projects)
尝试使用
encodeURIComponent
函数:Try to use the
encodeURIComponent
function:在您的 queryStr 上使用 JavaScript 中的
encodeURIComponent
函数来转义您的 queryStr 中可能存在的 URL 中不允许的字符。有关同一主题的其他信息,请参阅这篇文章。
Use the
encodeURIComponent
function in Javascript on your queryStr to escape the characters that are not allowed in URLs that might be in your queryStr.See this post for other info on the same topic.