Merging jQuery AJAX requests for Zend Framework
I have a Zend Fram开发者_JS百科ework based web application which is generating 3 separate AJAX requests to the server in addition to the main page request. This is causing a significant performance hit to the web server.
I would like to try and mitigate this by combining all 3 AJAX requests into a single request that can be received by my Zend Framework application and processed by the action stack as 3 separate requests.
Any suggestions for tools/techniques and pitfalls would be welcome.
From the top of my head:
- build a request stack or queue (js array)
- send requests to request stack instead of firing off an ajax request
- send an ajax request containing the request stack array
- loop through the array server side and follow instructions
That would be something like a mini job stack/queue for ajax requests.
I took Markus' advice and created 2 jQuery plugins, one for queuing the requests and one for posting them.
The Zend Framework application receives the requests and iterates through each one adding any return data to a universal response object which is JSON encoded and returned to the client.
var count = 0;
var requests = new Array();
// Add AJAX requests to the queue
(function($){$.fn.addAjaxRequest=function(callback, ajaxArgs, initialArgs) {
requests[count] = [callback, ajaxArgs, initialArgs];
count++;
}
})
(jQuery);
// Send the queued AJAX requests to MVC
(function($){$.fn.postAjaxRequests=function(host) {
var response = null;
var url = 'http://' + host + '/ajax/process-ajax-requests';
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
async: false,
data : ({data : requests}),
success: function(data) {
response = data;
}
});
return response;
}
})
(jQuery);
精彩评论