encodeURIComponent()不编码空格

Javascript encodeURIComponent() not encoding spaces

本文关键字:编码 空格 encodeURIComponent      更新时间:2023-09-26

我有一个带有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 Co.,New York, NY,生成的url是

http://example.com?place=ACME Co.%2CNew York%2C NY

看到空格是未编码的吗?我甚至试图添加place = place.replace(/'s/g, '+'),但编码后似乎不起作用。我做错了什么?谢谢你的帮助。

更新:

怪Firefox !发现空格被正确编码,但是Firefox没有显示编码的空格,即使它们是。在Internet Explorer 10Google Chrome中测试,它们都以编码格式显示空格。谢谢Adam的小提琴http://jsfiddle.net/VYDcv/

我不知道你看到了什么,但是encodeURIComponent确实转义空格字符。

根据您的代码:http://jsfiddle.net/VYDcv/

如果你输入"Hello world",它会提醒你空格替换为%20

报警结果:http://example.com?place=Hello%20World

当你设置你的浏览器的document.location.href,它可能会改变%20回到地址栏的一个空间,但它正在被javascript转义。

对我来说这是一个简单的解决方案:

<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>