jquery has enabled us to improve efficiency and reduce many compatibility problems while developing AJAX applications, but it's been a long time and we can't leave him. The encapsulation of a simple jquery Ajax request, for example, lets us forget the original XMLHttpRequest object and his attributes, methods, and keep us away from the truth of the matter.
In an AJAX project, you often encounter a message prompt that requires a server-side return error, or data such as a message code. Some help, solutions, many sites are returning the wrong message JSON data or script, this way when we use Jquery.ajax () when there is a problem, the Jquery.ajax () callback function success (data) of the data parameter may be xmldoc, Jsonobj, HTML, text, etc... It depends on our datatype settings and MIME. Many times our error handling is a unified process, no matter what you request is Xml,json .... Not only bad unity, but also prone to parsing errors and so on.
Referencing the Prototyp framework approach, a jquery error extension was made.
Principle: Prototype idea is to put the server processing results state information in the header, this way not only to ensure the reponse body clean, while adapting to Xml,json,html,text return.
The server side only needs Response.AddHeader ("Error-json", "{code:2001,msg: ' User settings is null! ', script: '} ');"
Implementation: In order not to affect the original Jquery.ajax method, while not destroying the jquery library source files, do the following extensions, the code is very simple to read:
;(function($){
var ajax=$.ajax;
$.ajax=function(s){
var old=s.error;
var errHeader=s.errorHeader||"Error-Json";
s.error=function(xhr,status,err){
var errMsg = window["eval"]("(" + xhr.getResponseHeader(errHeader) + ")");
old(xhr,status,errMsg||err);
}
ajax(s);
}
})(jQuery);