Javascript custom callback function and javascript callback function
Javascript callback function
If you call function a directly, this callback function will be suspended. However, using a function as a parameter has the following benefits: When a (B) is used, function B becomes a callback function, and you can use a (c) as a callback function, function c becomes the callback function. If you write functiona () {...; B () ;}, the flexibility of the variable is lost.
Function a (index, callback ){
Callback (index );
}
Function B (index ){
Alert (index );
}
A (10000, B );
What is the callback function in JavaScript?
Var req;
Function validate (){
Var idField = document. getElementById ("userid ");
Var url = "Validate. jsp? Id = "+ encodeURI (idField. value );
Init ();
Req. open ("GET", url, true );
Req. onreadystatechange = callback;
// Callback is the callback function. When req. onreadystatechange is triggered, callback is called to obtain the content returned by the url.
Req. send (null );
}
Function init (){
If (window. XMLHttpRequest ){
Req = new XMLHttpRequest ();
} Else if (window. ActiveXObject ){
Req = new ActiveXObject ("Microsoft. XMLHTTP ");
}
}
Function callback (){
If (req. readyState = 4) {// return to the Client
If (req. status = 200) {// the feedback is completely normal.
// Alert (req. responseText );
Var msg = req. responseXML. getElementsByTagName ("msg") [0];
// Alert (msg );
SetMsg (msg. childNodes [0]. nodeValue );
}
}
}
Function setMsg (msg) {// span <span id = "usermsg"> </span>
// Alert (msg );
Mdiv = document. getElementById ("usermsg ");
If (msg = "invalid "){
Mdiv. innerHTML = "<font color = 'red'> username exists </font> ";
} Else {
Mdiv. innerHTML = "<font color = 'green'> congratulations! You can use this username! </Font> ";
}
}
Validate. jsp
<%
Response. setContentType ("text/xml ");
Response. setHeader ("Cache-Control", "no-store"); // HTTP1.1
Response. setHeader ("Pragma", & quo ...... remaining full text>
Javascript callback function synchronization problems
First, javascript scripts are linearly executed.
<Javascript>
Operation
Operation B
Operation C
</Javascript>
If "A" is executed, B is executed before C is executed.
The reason why you say asynchronous occurs. Because you call the BMap. Map class getPoint is an ajax
This ajax is an http request. Javascript program execution is not restricted.
Because. GetPoint jumps out of this javascript script. Execute the script on your own, while the script continues with the next statement alert (d1)
So -----------
Function (point ){
If (point ){
Map. centerAndZoom (point, 16 );
Map. addOverlay (new BMap. Marker (point ));
D1 = point. lng;
}
}
----------------------
This method is executed only after ajax is reversed. Not working
So d1 does not = point. lng
If you obtain the d1 result of an ajax request
Please go
D1 = point. lng; followed:
Alert (d1 );