我在我的应用程序中实现谷歌的即时搜索。我希望在用户输入文本时触发HTTP请求。我遇到的唯一问题是,当用户在名字和姓氏之间找到空格时,空格没有被编码为+,从而破坏了搜索。我如何既可以替换空间与一个+,或只是安全URL编码字符串?
$("#search").keypress(function(){
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val();
var options = {};
$("#results").html(ajax_load).load(query);
});
encodeURIComponent对我来说很好。我们可以在ajax call中给出这样的url。代码如下所示:
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
更好的办法:
encodeURIComponent转义除以下字符外的所有字符:字母、十进制数字、- _。! ~ * ' ()
To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.
对于application/x-www-form-urlencoded (POST),根据http://www.w3.org/TR/html401/interac...m-content-type,空格将被“+”替换,因此可能希望在encodeURIComponent替换之后,将“%20”替换为“+”。
如果您希望更严格地遵守RFC 3986(保留!,',(,)和*),即使这些字符没有正式的URI分隔用途,也可以安全地使用以下字符:
function fixedEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
encodeURIComponent对我来说很好。我们可以在ajax call中给出这样的url。代码如下所示:
$.ajax({
cache: false,
type: "POST",
url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
dataType: "HTML",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});