我在我的应用程序中实现谷歌的即时搜索。我希望在用户输入文本时触发HTTP请求。我遇到的唯一问题是,当用户在名字和姓氏之间找到空格时,空格没有被编码为+,从而破坏了搜索。我如何既可以替换空间与一个+,或只是安全URL编码字符串?

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

当前回答

使用jQuery.param()…… 描述:创建数组、普通对象或适合在URL查询字符串或Ajax请求中使用的jQuery对象的序列化表示。在传递jQuery对象时,它应该包含带有名称/值属性的输入元素。

其他回答

试试这个

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

使用jQuery.param()…… 描述:创建数组、普通对象或适合在URL查询字符串或Ajax请求中使用的jQuery对象的序列化表示。在传递jQuery对象时,它应该包含带有名称/值属性的输入元素。

encodeURIComponent试试。

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

例子:

var encoded = encodeURIComponent(str);

I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded. I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)

硬编码URL,即>

 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) {.......});

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