URL 在 jQuery 中为 AJAX 请求编码一个字符串 [英] URL Encode a string in jQuery for an AJAX request

查看:21
本文介绍了URL 在 jQuery 中为 AJAX 请求编码一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在我的应用程序中实施 Google 的即时搜索.我想在用户输入文本时触发 HTTP 请求.我遇到的唯一问题是,当用户进入名字和姓氏之间的空格时,该空格不会被编码为 +,从而破坏了搜索.我怎样才能用 + 替换空格,或者只是安全地对字符串进行 URL 编码?

I'm implementing Google's Instant Search in my application. I'd like to fire off HTTP requests as the user types in the text input. The only problem I'm having is that when the user gets to a space in between first and last names, the space is not encoded as a +, thus breaking the search. How can I either replace the space with a +, or just safely URL Encode the string?

$("#search").keypress(function(){       
    var query = "{% url accounts.views.instasearch  %}?q=" + $('#tags').val();
    var options = {};
    $("#results").html(ajax_load).load(query);
});

推荐答案

尝试 encodeURIComponent.

通过用一个、两个、三个或四个表示字符的 UTF-8 编码的转义序列替换某些字符的每个实例来对统一资源标识符 (URI) 组件进行编码(对于由以下内容组成的字符,只有四个转义序列)两个代理"字符).

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

这篇关于URL 在 jQuery 中为 AJAX 请求编码一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆