Javascript URL 在 jQuery 中为 AJAX 请求编码一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6544564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
URL Encode a string in jQuery for an AJAX request
提问by Brian D
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?
我正在我的应用程序中实现 Google 的即时搜索。我想在用户输入文本时触发 HTTP 请求。我遇到的唯一问题是,当用户进入名字和姓氏之间的空格时,该空格不会编码为+
,从而破坏了搜索。我怎样才能用 a 替换空格+
,或者只是安全地对字符串进行 URL 编码?
$("#search").keypress(function(){
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val();
var options = {};
$("#results").html(ajax_load).load(query);
});
回答by Anders Fjeldstad
Try 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).
通过用一个、两个、三个或四个表示字符的 UTF-8 编码的转义序列替换某些字符的每个实例,对统一资源标识符 (URI) 组件进行编码(对于由两个“代理“ 人物)。
Example:
例子:
var encoded = encodeURIComponent(str);
回答by Praveen04
encodeURIComponentworks fine for me. we can give the url like this in ajax call.The code shown below:
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) {
}
});
回答by StackOverFlow
Better way:
更好的方法:
encodeURIComponentescapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
encodeURIComponent转义除以下字符之外的所有字符:alphabetic, decimal digits, - _ . ! ~ * ' ( )
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.
为了避免对服务器的意外请求,您应该对将作为 URI 的一部分传递的任何用户输入的参数调用 encodeURIComponent。例如,用户可以为可变注释键入“Thyme &time=again”。不在此变量上使用 encodeURIComponent 将再次给出 comment=Thyme%20&time=again。请注意,与号和等号标记了一个新的键值对。因此,不是让 POST 评论键等于“Thyme &time=again”,而是有两个 POST 键,一个等于“Thyme”,另一个(时间)等于 again。
For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac...m-content-type, spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".
对于 application/x-www-form-urlencoded (POST),根据http://www.w3.org/TR/html401/interac...m-content-type,空格将替换为“+”,因此人们可能希望在 encodeURIComponent 替换之后用“+”额外替换“%20”。
If one wishes to be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
如果希望更严格地遵守 RFC 3986(保留 !、'、(、) 和 *),即使这些字符没有正式的 URI 分隔用途,也可以安全地使用以下内容:
function fixedEncodeURIComponent (str) {
return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}
回答by d1jhoni1b
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)
我使用 MVC3/EntityFramework 作为后端,前端通过 jquery 使用我所有的项目控制器,当您直接传递除 URL 硬编码以外的参数时,直接发布(使用 $.post)不需要数据加密。我已经测试了几个字符,我什至发送了一个 URL(这个http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1)作为参数并且有即使当您在 URL 中传递所有数据(硬编码)时 encodeURIComponent 工作得很好,也完全没有问题
Hardcoded URL i.e.>
硬编码的 URL ie>
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;
Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
否则不要使用 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) {.......});
回答by genesis
try this one
试试这个
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val().replace(/ /g, '+');