jQuery's $.ajax URL Encoding Problems

旧街凉风 提交于 2019-12-06 17:12:16

问题


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.

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.

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:

http://localhost:8080/rest/123/Product%20Line%20A/%5BProduct%20Type%20B%5D

Chrome, Safari and IE POSTS the URL in the following format:

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?

Thanks in advance!


回答1:


You can use javascript's encodeURI() function to encode a URL into "Firefox format" as you state.




回答2:


Passing [Product Type B] in unencoded form is invalid, so what the browsers make of it is undefined.

Do a encodeURIComponent() on the product type part.




回答3:


I think .serialize() would be the jquery way to do this.

check here: http://api.jquery.com/serialize/

also there is a plugin for jquery: http://plugins.jquery.com/project/URLEncode

or the javascript way ... encodeURIComponent()

check here: http://www.w3schools.com/jsref/jsref_encodeURI.asp




回答4:


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 original function.



来源:https://stackoverflow.com/questions/4485808/jquerys-ajax-url-encoding-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!