Home >Web Front-end >JS Tutorial >Is It Possible to Define jQuery AJAX Success Callback Functions Externally?
Defining Success Callback Functions for jQuery AJAX
When retrieving data from a server using jQuery AJAX, developers often define the success callback function within the .ajax() block. However, is it possible to define the callback function externally?
External Callback Function
The provided code snippet attempts to define the success callback function outside the .ajax() block:
var dataFromServer; //declare the variable first function getData() { $.ajax({ url : 'example.com', type: 'GET', success : handleData(dataFromServer) }) } function handleData(data) { alert(data); //do some stuff }
Recommendation: Use Deferred Objects
While the code snippet may technically work, it is no longer recommended to define the success callback outside the .ajax() block. Instead, use deferred objects:
function getData() { return $.ajax({ url : 'example.com', type: 'GET' }); } function handleData(data /* , textStatus, jqXHR */ ) { alert(data); //do some stuff } getData().done(handleData);
Deferred objects provide several advantages:
Using deferred objects offers greater flexibility and control over AJAX callback handling, making it a more robust and modern approach.
The above is the detailed content of Is It Possible to Define jQuery AJAX Success Callback Functions Externally?. For more information, please follow other related articles on the PHP Chinese website!