14.02.2014

jQuery.ajax или как заставить передавать первым аргументом ссылку на xhr

По хорошему — никак. Но!

#1.
Как делал я.

#1. Как делал я

			$.ajaxPrefilter(function (options, originalOptions, xhr){
				options.dataTypes	= [];
				options.dataFilter	= function (){
					return	xhr;
				};
			});
		

#1. Как делал я

Плюсы

#1. Как делал я

			$.ajaxPrefilter(function (options, originalOptions, xhr){
				options.dataTypes	= ["xxx"];
				options.dataFilter	= function (result){
					xhr.body = result;
					return	xhr;
				};
			});
		

#1. Как делал я

			$.ajaxSetup({
				"converters": {
					"* xxx": function (xhr){
						if( /json/i.test(xhr.getResponseHeader("content-type") ){
							// Без try catch, да-да!
							xhr.body = JSON.parse(xhr.body);
						}
						return xhr;
					}
				}
			});
		

#2.
Как делалют нормальные.

Переопределить jQuery.ajax

			(function ($, originalAjax){
				$.ajax = function (){
					var xhr = originalAjax.apply($, arguments);
					$.extend(xhr, xhr.then( // заменяем методы done/fail/progress
						function (){ return $.Deferred().resolve(xhr); },
						function (){ return $.Deferred().reject(xhr); })
					);
					return xhr;
				};
			})(jQuery, jQuery.ajax)
		

Переопределить jQuery.ajax

Минусы:

The End

Если знаете как сделать это лучше, пишите!

github.com/RubaXa
@ibnRubaXa