URL在jQuery中为AJAX请求编码一个string

我正在应用程序中实施Google的即时search。 我想在用户input文本时inputHTTP请求。 我唯一的问题是,当用户到第一个和最后一个名字之间的空间时,该空间不被编码为+ ,从而中断search。 我怎样才能用+ ,或只是安全的URLreplace空间编码string?

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

尝试encodeURIComponent 。

编码统一资源标识符(URI)组件,通过用代表该字符的UTF-8编码的一个,两个,三个或四个转义序列replace某些字符的每个实例(将只有四个转义序列用于由两个“代理“字符)。

例:

 var encoded = encodeURIComponent(str); 

encodeURIComponent对我来说工作正常。 我们可以在ajax调用中给出这样的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转义除下列字符以外的所有字符: alphabetic, decimal digits, - _ . ! ~ * ' ( ) alphabetic, decimal digits, - _ . ! ~ * ' ( )

为了避免对服务器的意外请求,您应该在任何用户input的参数上调用encodeURIComponent,这些参数将作为URI的一部分传递。 例如,用户可以为variables注释键入“Thyme&time = again”。 不在这个variables上使用encodeURIComponent会给予comment = Thyme%20&time = again。 请注意,&号和等号标记了一个新的键和值对。 因此,您不必拥有一个等于“Thyme&time = again”的POST注释键,而是有两个POST键,一个等于“Thyme”,另一个等于一个(时间)。

对于application / x-www-form-urlencoded(POST),根据http://www.w3.org/TR/html401/interac…m-content-type ,空格将被replace为'+',所以人们可能希望跟随一个encodeURIComponentreplace,并用“+”替代“%20”。

如果希望在遵守RFC 3986(保留!,',(,)和*)方面更加严格,即使这些字符没有forms化的URI定界用法,也可以安全地使用以下内容:

 function fixedEncodeURIComponent (str) { return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A"); } 

我使用MVC3 / EntityFramework作为后端,前端通过jQuery使用我所有的项目控制器,直接发布(使用$ .post)不需要数据编写,当你直接传递参数而不是URL硬编码。 我已经testing了几个字符,我甚至发送了一个URL(这个http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1 )作为参数,即使encodeURIComponent在URL中传递所有数据时工作得很好(硬编码)

硬编码urlie>

  var encodedName = encodeURIComponent(name); var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent; 

否则不要使用encodeURIComponent,而是尝试在ajax post方法中传递参数

  var url = "ControllerName/ActionName/"; $.post(url, { name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent }, function (data) {.......}); 

试试这个

 var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val().replace(/ /g, '+');