How do we write out Ajax Call usually
- $.ajax({
- type: 'POST',
- url: 'handler.ashx',
- contentType: 'application/json',
- dataType: 'json',
- processData: false,
- data: "{}",
- //Other code
- success: function (response) {
- // Update the UI here to reflect that the request was successful.
- var result = eval('(' + response.d + ')');
- },
- error: function (xmlHttpRequest, textStatus, errorThrown) {
- if (xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0)
- return true; // it's not really an error ***Browser reload or exit
- else {
- // Update the UI here to reflect that the request was unsuccessful
- AJAXERROR('[function NAme]::' + xmlHttpRequest.responseText + '::[thrownerror]::' + errorThrown);
- }
- }
- });
Now lets take advantage of the jQuery.ajaxSetup() using this function you can predefine you common code in the Ajax call
Now i will take my normal code and use it in Ajax Setup
- $.ajaxSetup({
- type: 'POST',
- contentType: 'application/json',
- dataType: 'json',
- processData: false,
- data: "{}",
- error: function (xmlHttpRequest, textStatus, errorThrown) {
- if (xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0)
- return true; // it's not really an error ***Browser reload or exit
- else {
- // Update the UI here to reflect that the request was unsuccessful
- var fnName = arguments.callee.toString();
- fnName = fnName.substr('function '.length);
- fnName = fnName.substr(0, myName.indexOf('('));
- alert('' + xmlHttpRequest.responseText + '::[thrownerror]::' + errorThrown);
- }
- }
- });
I use same error function to all so i have added it if you dont need it You can remove it or override it in the Ajax Call Later
As you can see i Have defined most of my Ajax options in the ajaxSetup.Now lets See how the Ajax Call reduces
- $.ajax({
- url: 'handler.ashx',
- //Other code
- success: function (response) {
- // Update the UI here to reflect that the request was successful.
- var result = eval('(' + response.d + ')');
- //Do needed
- }
- });
As you can see we have reducd almost 12 line of code
if we have 10 ajax functions then 12*10 = 120-12=108lines
the size of the file may not decrese by huge.but we can save the last few bytes of Javascript file.
Please provide your FeedBack will meet you in next Post
0 comments:
Post a Comment