Observation function
The ajaxStart and ajaxStop functions can be used as observation functions, and we can use the callback function of the observation function to perform corresponding processing.
The callback function of ajaxStart is triggered when the Ajax request starts and no other transmission has been made.
When the last active request terminates, the callback function registered through ajaxStop is executed.
Since the observation function is global, it needs to be called using $(document). We test the two functions by using the Ajax method to obtain an image example:
The current page is:
<div></div> <button>load</button>
The content of test.html in the same directory is:
<img src="avatar.jpg" />
Want to load an image after clicking the button:
$('button').click(function() { $('div').load('test.html'); });
At this point we can use the ajaxStart and ajaxStop functions to add prompts:
$(document).ajaxStart(function() {// alert('load a picture'); }).ajaxStop(function() { alert('show a picture'); }); $('button').click(function() { $('div').load('test.html'); });
After clicking the button at this time, it will prompt load a picture before loading the image, and show a picture after loading.
Error handling
The most commonly used method is the global ajaxError method. Take the above example as an example. If we send a data request to a page that does not exist:
$(document).ajaxError(function() {// alert('load failed!'); }); $('button').click(function() { $('div').load('noexsited.html'); });
After clicking the button at this time:
For non-load methods, you can also use the fail method for concatenation processing:
$('button').click(function() { $.get('noexsited.html', function(data) { }).fail(function(jqXHR) { alert('status is ' + jqXHR.status); }); });
JSONP
JSONP is JSON with padding, padded JSON, which uses the