Extending jQuery's $.post() function
I've been using jQuery for a while now, but I've never gotten too advanced with it.
How can I extend the $.post() function to add my own functionality to it?
The main thing I'm intere开发者_如何学Gosted in adding at the moment is some $.log() calls so I can see what's going on on the iPad, but I'd also be interested in up some "loading" icons, and maybe looking at some caching too.
I've done a similar thing with the jQuery $.ajax method. I created new top level method on the jQuery object:
$.extend({ myAjax: function(options) {
// code I want to run before the jQuery AJAX,
// I can access and alter the options passed in
var jqXHR = $.ajax(myAjax);
// code I want to run after the jQuery AJAX
// I can also run jQuery deferred code, e.g: jqXHR.done(function() { something });
});
You can then call this via:
var options = {
url: "http://example.com",
type: "GET",
dataType: "JSONP"
}
$.myAjax(options);
Where I wrapped my additional functionality around the jQuery AJAX function. This enabled me to choose between using the augmented function or falling back to the basic jQuery function. It also ensures compatibility with plugins, existing code etc.
For the loading icons, look into .ajaxStart() and .ajaxStop().
For defining a universal action to take after any $.post()
, you probably don't need to do anything fancy either. Just use $.ajaxSetup() to define success/error handlers to do that logging after every request, in addition to the handler that each specific $.post()
registers.
Also, related to debugging on an iPad, check out JSConsole. It's insanely helpful for debugging JavaScript on devices where you can't use in-browser debugging tools, like mobile development.
精彩评论