Home >Web Front-end >JS Tutorial >How to Define jQuery AJAX Success Callback Function Outside of .ajax() Block?
jQuery AJAX Success Callback Function Definition Outside .ajax() Block
In jQuery, you can retrieve data from a server using the $.ajax() method. Typically, the success callback function is defined within the .ajax() block. However, it is possible to define the callback outside the block.
Defining the Callback Function Outside the .ajax() Block
To define the success callback outside the .ajax() block, you should return the result of $.ajax() as follows:
<code class="javascript">function getData() { return $.ajax({ url: 'example.com', type: 'GET' }); }</code>
Then, you can use the .done() method to add the callback outside the .ajax() call:
<code class="javascript">getData().done(handleData);</code>
Handling the Data
The handleData function can be defined as follows:
<code class="javascript">function handleData(data) { alert(data); // Do other stuff }</code>
The data passed to the handleData function is the data returned from the server.
Benefits of Defining the Callback Outside the .ajax() Block
Defining the callback outside the .ajax() block provides several benefits:
Example
The following code demonstrates how to use this technique:
<code class="javascript">// A trivial timer for demo purposes var timer = $.Deferred(); setTimeout(timer.resolve, 5000); // Add a `done` and an `error` handler to the AJAX call var ajax = getData().done(handleData).fail(error); // Wait for both the AJAX call and the timer to finish $.when(timer, ajax).done(function() { // Both operations have finished }); // Add an additional `done` handler to the AJAX call ajax.done(function() { // Can be added even if the AJAX call has already finished });</code>
This technique can be useful for decoupling AJAX functionality from the subsequent actions and for synchronizing multiple asynchronous operations.
The above is the detailed content of How to Define jQuery AJAX Success Callback Function Outside of .ajax() Block?. For more information, please follow other related articles on the PHP Chinese website!