使用以下代码,我将用户重定向到一个 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]=
如您所见,我无法获取,我对 queryString 进行了编码:
$.param(requestObject);
当我对它进行 console.log 时,它会按原样显示。但是当我将它传递给 location.replace() 时,它是一团糟。我尝试使用 JS 原生 encodeURI 手动构建它,但这没有帮助。
如果你能帮助我,我会很高兴。
最佳答案
在您的 queryStr 上使用 Javascript 中的 encodeURIComponent
函数来转义可能在您的 queryStr 中的 URL 中不允许的字符。
location.replace('http://' + location.host + '/path/to/file.php?' + encodeURIComponent(queryStr));
参见 this post有关同一主题的其他信息。
关于JavaScript window.location 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6704362/