Ajax callback module and call module

Source: Internet
Author: User
Tags call back

Ajax callback module and call moduleAuthor: clear date: font size: Small Medium large

These days I 've been busy working to modularize all Ajax applications, and then I 've carefully studied Dave Crane, Eric pascarello, Darren
<Ajax in
After the action>, I found that foreigners are really cool. Compared with the other five Ajax books, this book is completely a class-level book, which is very pediatric.

Describe what I learned from the bottom:
The first step is completely modular writing. You can steal some simplified ideas from prototype and start with the code.

The Declaration ID is indispensable in the program that writes the call object. Currently, I write it like this:

Program code function $ (objid ){
Return document. getelementbyid (objid)
}

$ (Idname) Is it much more convenient to call the ID in the future.

The classic location is here:

Program code function $ (){
Return document. getelementbyid (arguments [0])
}

This
Sample writing is also acceptable. Many people do not know what arguments is. In fact, they are the corresponding array of function parameters. The first parameter is arguments [0], and the second parameter is
Arguments [1], and so on. However, arguments is a pseudo array and cannot be operated directly by arrays.
This will be explained in a log.

According to this idea, I wrote another function that defines the Tag Name:

Program code function $ F (objname ){
Return document. getelementsbyname (objname) [0]
}

Getelementsbyname is an array object that calls all tag names in HTML. You can specify the tag name to find the object.

Now, start the callback function module.
It is estimated that many people have used Windows. onload, while in a large project, it may be designed to require many functions of onload, but it is impossible to use different onload for each page, because it will be very troublesome to do so. so we need to think of a way of thinking about how to call back functions as needed.
First look at the Code:

Program code window. $ loads = new array ()
Window. $ load = function (func, ARG ){
Window. $ loads [window. $ loads. Length] = [func, (ARG )? Arg: ""];
}
Window. onload = function (){
For (VAR I = 0; I <window. $ loads. length; I ++ ){
VaR func = Window. $ loads [I] [0];
Func (window. $ loads [I] [1])
}
}

You should know how to do it now. when a page is loaded, the window content is always loaded first. Therefore, we expand a window object array and dynamically write the callback function to be used in different locations as needed. Once the page is loaded, you can load only the required functions on this page.
The loading method is to write window. $ load (funcname, argument) on different pages. Is it convenient.
I have extended this module to load function parameters. Of course, you do not need to write argument when loading parameters.
The idea of this module is to use an onload loop to read the functions to be loaded from the array and then run them one by one.

Ajax
The core function call of is to interact with the server through the backend Js. We may need to call different servers and implement different functions, and write many similar core call codes, no
This only increases the workload and makes code maintenance inconvenient in the future. I also expanded the code on Dave's idea and can use this module to call different Ajax core data.
You can also customize the actions required for different call states.

Code:

Program code // Ajax component
VaR Ajax = new object ();
Ajax. $ x = function (URL, onload, onerror, statearray ){
This. url = URL;
This. Req = NULL;
This. onload = onload;
This. onerror = (onerror )? Onerror: This. defaulterror;
This. statenum = (statearray )? Statearray: false;
This. loadxmldoc (URL );
}
Ajax. $ X. Prototype = {
Loadxmldoc: function (URL ){
If (window. XMLHttpRequest ){
This. Req = new XMLHttpRequest ();
If (this. Req. overridemimetype ){
This. Req. overridemimetype ('text/xml ');
}
} Else if (window. activexobject ){
Try {
This. Req = new activexobject ("msxml3.xmlhttp ");
} Catch (e ){
Try {
This. Req = new activexobject ("msxml2.xmlhttp ");
} Catch (e ){
Try {
This. Req = new activexobject ("Microsoft. XMLHTTP ");
} Catch (e ){}
}
}
}
If (this. req ){
Try {
VaR loader = this;
This. Req. onreadystatechange = function (){
Loader. onreadystate. Call (loader)
}
This. Req. Open ("get", URL, true );
This. Req. Send (null );
} Catch (ERR ){
This. onerror. Call (this );
}
}
},
Onreadystate: function (){
VaR Req = This. req;
VaR ready = Req. readystate;
If (this. statenum & ready> = 1 & ready <= 3 ){
This. statenum [ready-1]. Call (this );
} Else if (ready = 4 ){
VaR httpstatus = Req. status;
If (httpstatus = 200 | httpstatus = 0 ){
This. onload. Call (this );
} Else {
This. onerror. Call (this );
}
}
},
Defaulterror: function (){
Alert ("data connection error! "
+ "/N/nreadystate:" + this. Req. readystate
+ "/Nstatus:" + this. Req. Status
+ "/Nheafers:" + this. Req. getAllResponseHeaders ()
)
}
}

No
This code can basically satisfy all your core Ajax data calling functions without modification. This idea is the traditional OOP (Object-Oriented
Object-oriented
Programming) programming ideas. maybe you think it's incredible. Yeah, I was scared by OOP before, but after getting started with a lot of programming languages, I found that this is a very good idea, and I also
He was very happy to accept it. I can say that when you have a certain ideological consciousness, you can easily master the program. when JavaScript uses this idea, believe in the traditional
Programmers are also ashamed to despise Js.

I only want to talk about the call method of this control. Use the verification code prompt as an example. I haven't sent this item yet!

Program code // check whether the verification code is correct or not
Function checkcode (){
// Set the server URL for data exchange
VaR url = "common/checkcode. asp? Timestamp = "+ new date (). gettime ();
// Call the Ajax Data Core Module
// The first parameter is the URL address,
// The second parameter is the name of the function to be called after Ajax data is successfully interacted with the server.
// The third parameter is the name of the function called for Ajax Data Interaction failure. Of course, you can leave it empty because I have defined a default error processing function in the module.
//
The fourth parameter is the function that you need to call in every state during the data calling process. You can also leave it empty, so no other State callback is used. Remember that this is an array name, you need to follow this
Method To write the callback function for each status: tocheck1 function () {}, Function
Tocheck2 () {}, function tocheck3 () {}, remember!
VaR checks = new Ajax. $ X (URL, tocheck, tocheckerror)
}
// Callback function after successful data call
Function tocheck (){
VaR res = this.req.responsexml.doc umentelement;
VaR vadcode = res. getelementsbytagname ("codes") [0]. firstchild. nodevalue;
VaR newtxt = Document. Forms [0]. Validate. value. tolowercase ()
If (newtxt = vadcode ){
$ ("Codetxt"). innerhtml = "the verification code is correct! ";
} Else if (newtxt. Length <4 ){
$ ("Codetxt"). innerhtml = "the verification code is incomplete! "
} Else {
$ ("Codetxt"). innerhtml = "Incorrect verification code! Tip: <label ondblclick = 'tocopycode (this); '> "+ vadcode +" </label>"
}
}
// This is a small egg. You can find it.
Function tocopycode (thiscode ){
Document. Forms [0]. Validate. value = thiscode. innerhtml;
$ ("Codetxt"). innerhtml = "the verification code is correct! ";
}
// Handle data call failures
Function tocheckerror (){
$ ("Codetxt"). innerhtml = "Verification code check error! ";
}
VaR oldcom, timeid
// This is the action that needs to be called to detect the verification code you entered.
Function oncomchange (){
VaR inputxt = Document. Forms [0]. Validate. Value
If (inputxt! = Oldcom & trim (inputxt )! = ""){
Oldcom = inputxt;
Checkcode ("recode ")
} Else if (inputxt. Length = 0 ){
$ ("Codetxt"). innerhtml = "Enter the verification code! "
}
Timeid = setTimeout (oncomchange, 100)
}
// When you leave the verification code box, stop the verification.
Function onblurs (){
Cleartimeout (timeid)
}

Maybe you still have a lot of questions. If you want to learn this, I believe you can understand it. I believe that people who rely only on copying other people's code can understand it clearly.

Technology is always a technology, and it is the foundation for you to embark on the management business. believe that a non-technical enterprise manager must be inferior to a technical enterprise manager. when you have both strong technologies, wise management, and a keen sense of market, congratulations! You have succeeded!

And I am infinitely close to this goal!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.