我有一个带有id txtPlace的文本输入的表单,用户将输入输入作为url查询传递给服务器。我尝试使用encodeURIComponent(),但它不是编码空间。这是我的简化代码
<div class="searchBoxRow">
<input type="text" id="txtPlace" size="55" placeholder="Enter place to search"/>
<a href="#" id="btnSearch">Search</a>
</div>这是我的javascript
<script type="text/javascript">
$(function () {
$('#btnSearch').on('click', function (e) {
e.preventDefault;
var place = encodeURIComponent($('#txtPlace').val());
var url = "http://example.com?place=" + place;
document.location.href = url;
});
});
</script>如果用户键入ACME .,纽约,纽约,生成的url为
http://example.com?place=ACME公司%2 2CNew%2C NY
看到空格是未编码的了吗?我甚至试图添加place = place.replace(/\s/g, '+'),但在编码之后,这似乎不起作用。我做错了什么?谢谢你的帮助。
更新:
指责火狐!发现这些空间被正确地编码了,但是火狐并没有显示被编码的空格,尽管它们是编码的。在、Internet 10和Google 中进行测试,它们都以编码格式显示空间。谢谢亚当的小提琴http://jsfiddle.net/VYDcv/
发布于 2013-05-16 22:24:04
我不知道你看到了什么,但encodeURIComponent确实转义了空间字符。
请看这个小提琴,基于您的代码:http://jsfiddle.net/VYDcv/
如果您键入"Hello“,它将用%20替换的空格提醒您。
警报结果:http://example.com?place=Hello%20World
当您设置浏览器的document.location.href时,它可能会将%20更改回地址栏中的一个空格,但它是由javascript转义的。
发布于 2013-05-16 22:24:52
对我来说,这是一个简单的解决方案:
<script type="text/javascript">
$(function () {
$('#btnSearch').on('click', function (e) {
e.preventDefault;
var place = encodeURIComponent($('#txtPlace').val());
place=place.replace(" ", "+"); //or .replace(" ", "%20")
var url = "http://example.com?place=" + place;
document.location.href = url;
});
});
</script>https://stackoverflow.com/questions/16598382
复制相似问题