jQuery 的 $.ajax URL 编码问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4485808/
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
jQuery's $.ajax URL Encoding Problems
提问by schone
I'm using jQuery's $.ajax method to send and retrieve data to a REST service. Some of the URL's I'm providing to the $.ajax method requires spaces and other special characters to be encoded.
我正在使用 jQuery 的 $.ajax 方法向 REST 服务发送和检索数据。我提供给 $.ajax 方法的一些 URL 需要对空格和其他特殊字符进行编码。
The problem lies with Chrome, Safari (Webkit) and Internet Explorer browsers. Firefox POST's to a URL which is encoded but the other browsers POST to a URL which isn't encoded.
问题在于 Chrome、Safari (Webkit) 和 Internet Explorer 浏览器。Firefox POST 到已编码的 URL,但其他浏览器 POST 到未编码的 URL。
As an example:
举个例子:
$.ajax ({
url: "http://localhost:8080/rest/123/Product Line A/[Product Type B]",
type: "POST",
dataType: "json",
data: { ... },
success: function(...){},
error: function(...){}
})
Firefox POSTS the URL in the following format:
Firefox 以以下格式发布 URL:
http://localhost:8080/rest/123/Product%20Line%20A/%5BProduct%20Type%20B%5D
Chrome, Safari and IE POSTS the URL in the following format:
Chrome、Safari 和 IE 以以下格式发布 URL:
http://localhost:8080/rest/123/Product Line A/[Product Type B]
The REST services accepts the encoded (Firefox) format - is there a way I can make this consistent across all browsers?
REST 服务接受编码 (Firefox) 格式 - 有没有一种方法可以使其在所有浏览器中保持一致?
Thanks in advance!
提前致谢!
回答by Aatch
You can use javascript's encodeURI()
function to encode a URL into "Firefox format" as you state.
您可以使用 javascript 的encodeURI()
函数将 URL 编码为“Firefox 格式”,如您所说。
回答by Pekka
Passing [Product Type B]
in unencoded form is invalid, so what the browsers make of it is undefined.
[Product Type B]
以未编码形式传递是无效的,因此浏览器对其进行的处理是未定义的。
Do a encodeURIComponent()
on the product type part.
encodeURIComponent()
在产品类型部分做一个。
回答by mahatmanich
I think .serialize() would be the jquery way to do this.
我认为 .serialize() 将是执行此操作的 jquery 方式。
check here: http://api.jquery.com/serialize/
在这里检查:http: //api.jquery.com/serialize/
also there is a plugin for jquery: http://plugins.jquery.com/project/URLEncode
还有一个 jquery 插件:http: //plugins.jquery.com/project/URLEncode
or the javascript way ... encodeURIComponent()
或 javascript 方式... encodeURIComponent()
check here: http://www.w3schools.com/jsref/jsref_encodeURI.asp
回答by Alex Wright
The quick fix would be to encodeURI()
the URL before passing to $.ajax. You could also replace the $.ajax function with a thin wrapper to take the {} literal and encodeURI the URL before passing to the originalfunction.
快速修复是encodeURI()
在传递给 $.ajax 之前的 URL。您还可以使用瘦包装器替换 $.ajax 函数,以在传递给原始函数之前获取 {} 文字和 encodeURI 的 URL 。