When using jquery, use the concept of Callback (), the callback function. and a lot.
For example:
$.ajax ({url: "Test.json", type: "GET", data: {username:$ ("#username"). Val ()}, DataType: "JSON", Beforsend:function//function (msg) {// The callback function called after the request completes (called when the request succeeds or fails) }, Error:function (msg) {// function called when request fails function (msg) { // callback function called after successful request
callback function Everyone will use, but jquery encapsulation, you can not let everyone understand the real use of the callback function. The JS Api explains this:a callback is a function, which is passed as an argument to another function and are executed after its The parent function has completed. of course, we can actually try out the magic of the callback function in JS. If you call it directly in function A, the callback function is limited to death. But using the function to do the argument has the following advantages: When you have a (b) function B is a callback function, and you can also a (c) this time, function c is a callback function. If you write function a () {...; b ();} The flexibility of the variable is lost. Here's the code:
<!DOCTYPE HTML><Html><Head><MetaCharSet= "GBK"/><Title> Callback function (callback)</Title><ScriptType= "Text/javascript"Src= "Jquery-1.4.4.min.js"></Script><ScriptLanguage= "JavaScript"Type= "Text/javascript">VarFfunctionD () {alert ("I'm a function of the jquery definition"); }VarE=function() {Alert ("I'm also a function of the jquery definition"); }functionA (callback) {alert ("I am the parent function A!"); Alert"Call callback function");//Callback ();$("#id"). Load ("Page parameter"); D ();//WorkIf(typeofCallback==="function"{alert (callback);}}functionB () {Alert ("I'm the callback function, B."); $("#id"). Load ("Page parameter"); E ();//does not work}functionC () {alert ("I'm the callback function C."); D ();//does not workf ();//does not work}functionTest () {a (b); a (c);} $ (function() {F=function() {Alert ("I am the callback function f"); } });</Script></Head><Body><H1> Learning JS callback function</h1> <button onclick= Test () >click me</ button> <p> should see a call to two callback functions </ p> </body> </html< Span style= "color: #0000ff;" >>
As
you can see, Iwrote jquery's Ajax functions in a (callback), B (), C () method, and note that this is the function of Ajax. There is a difference, I call the built-in function separately, and my own defined function. The
difference is here, because jquery and JS use the same callback, so in this case, jquery's built-in function will be called.
but the function that you define is not recognized, even if it is not called.(after this paragraph is not very understanding, hope to see the master please analyze)
so pay attention to this at the time of the callback.
JS callback function (callback)