Reasons not to use native XMLHttpRequest - why is $.ajax mandatory?

倾然丶 夕夏残阳落幕 提交于 2019-12-05 06:44:59

That's the only thing necessary for cross-browser support unless you need to support really old IEs (which apparently use a different ActiveXObject).

However, using e.g. jQuery provides a bunch of additional advantages:

  • Single function call, no unnecessary variables cluttering your scope.
  • Automated serialization of objects into GET/POST arguments. Why do that manually (you need to encode the values properly!) when you can simply pass an object?
  • Automated parsing of the response, e.g. in case of JSON you get an object and not just a string you need to parse manually.
  • Nice callbacks for common events (success/failure/finished)
  • Pluggable architecture to support e.g. XDomainRequest for CORS in IE.

Since you mention that you cannot use jQuery because your app will be embedded in another site that might conflict with it: You can avoid this by including jQuery and then using $.noConflict(true) to restore both the old $ and jQuery variables. To use it in your code you then write it like this:

(function($) {

})(jQuery.noConflict(true));

The XMLHttpRequest object is defined as a W3C standard here:

http://www.w3.org/TR/XMLHttpRequest2/

and thus the API itself should be consistent across browsers.

The only change should be, as you mentioned, how you obtain the XMLHttpRequest object. See here:

http://www.quirksmode.org/js/xmlhttp.html

for a cross-browser, non-jQuery way of doing it (obtaining the object is done in his XMLHttpFactories array.

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