A general ajax event may have already written a success during the development process. In subsequent development, I may not want to change the success method I wrote earlier. I want to restart a success, for example, the following code:
The code is as follows: |
Copy code |
$ ('. Btn'). click (function (){ $. Ajax ({ Type: 'post ', Url: 'Test. Php ', Data: $ ('form'). serialize (), Success: function (data ){ Console. log (data + '1 '); }, Success: function (data ){ Console. log (data + '2 '); } }); }); The test result is: {"User": "admin", "email": "1054770532@qq.com"} 2 |
We found that the subsequent success method overwrites the previous success method, and the test failed. Is there any way to write multiple success statements? Since jquery can be widely used around the world, this small demand can still be met. Here we use today's focus: jqXHR. Let's take a look at a piece of code to learn about jqXHR.
The code is as follows: |
Copy code |
$ ('. Btn'). click (function (){ Var jqXHR = $. ajax ({ Type: 'post ', Url: 'Test. Php ', Data: $ ('form'). serialize () }); JqXHR. success (function (data ){ Console. log (data + '1 '); }); JqXHR. success (function (data ){ Console. log (data + '2 '); }); }); The result is as follows: {"User": "tuisiyuan", "email": "1054770532@qq.com"} 1 {"User": "tuisiyuan", "email": "1054770532@qq.com"} 2 |
From above, we can easily find that the so-called jqXHR is just the return value of $. ajax, and both success methods are executed sequentially.
The jquery version is improved accordingly. In the future, jqXHR may discard the success, complete, and error methods, instead of the done, always, and fail methods.
The code is as follows: |
Copy code |
$ ('. Btn'). click (function (){ Var jqXHR = $. ajax ({ Type: 'post ', Url: 'Test. Php ', Data: $ ('form'). serialize () }); // Done => success, always => complete, fail => error JqXHR. always (function (data ){ Console. log ('always: '+ data ); }). Done (function (data ){ Console. log ('done: '+ data) }); JqXHR. done (function (data ){ Console. log ('done: '+ data ); }); JqXHR. fail (function (data ){ Console. log ('fail: '+ data ); }); }); |
JqXHR can be concatenated to execute multiple Dones.