繁体   English   中英

Javascript URIComponent重定向问题

[英]Javascript encodeURIComponent issue on redirection

我在jquery和php中使用了一个搜索框,当您在此搜索框中键入内容时,jquery会准备查询并重定向位置。 准备查询部分效果很好,但是重定向部分的编码查询有问题。 页面在重定向之前会自动对编码的查询进行解码。

如果在搜索框中键入“ test1 test2 test3”,它会使用encodeURIComponent()成功将查询编码为test1%20test2%20test3。

现在页面将自己重定向到result.php + query。 我的问题是页面转到result.php?q = test1 test2 test3而不是result.php?q = test1%20test2%20test3。

这是代码

 if($("#searchbox").val() != "")
 {
    var mq1 = encodeURIComponent($("#searchbox").val());
    var query = "q="+mq1;

 }

 alert(query);
 if(query!="")
 location = "result.php?"+query;

警报结果是q = test1%20test2%20test3,但结果为php?q = test1 test2 test3

编辑:如果我使用带有重定向代码的encodeURIComponent函数,则效果很好。

 alert(query);
 if(query!="")
 location = "result.php?"+encodeURIComponentquery);

这些代码有效,但也编码q = part。

我认为可能只是浏览器在地址栏中显示了test1 test2 test3 ,但是服务器获取了正确的值。 您可以通过浏览器开发工具(例如firebug)进行检查,甚至可以在服务器中进行检查。

为什么不将其更改为result.php?q=+encodeURIComponent(query)

由于您使用的是jQuery,为什么不这样写:

if ($("#searchbox").val()) {
    location = 'result.php?' + $.param({
        q: $("#searchbox").val()
    });
}

这是您编写的内容的一种变体-输入查询后,它会等待按下回车键(因为我不确定您的代码的上下文,是否位于表单的Submit方法中):

$('#searchbox').keypress(function(e) {
   if(e.which == 13 && $(this) {
       $(this).blur();
       var mq1 = encodeURIComponent($(this).val());
       var query = "q="+mq1;
       window.location = "result.php?"+ query;
   }
});

使用它创建以下URL:

result.php?q=multiple%20words%20in%20the%20url%20work%20fine

``我认为您的代码几乎在那里,但是围绕IF语句的逻辑正在引起问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM