我正在我的应用程序中实现 Google 的即时搜索。我想在用户输入文本输入时触发 HTTP 请求。我遇到的唯一问题是,当用户到达名字和姓氏之间的空格时,该空格没有被编码为 +
,从而中断了搜索。如何用 +
替换空格,或者只是安全地对字符串进行 URL 编码?
$("#search").keypress(function(){
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val();
var options = {};
$("#results").html(ajax_load).load(query);
});
最佳答案
试试 encodeURIComponent .
Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).
例子:
var encoded = encodeURIComponent(str);
关于javascript - URL 为 AJAX 请求在 jQuery 中编码一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6544564/