One week learn Mootools 1.4 Chinese tutorial :( 5) Ajax

Source: Internet
Author: User
Tags mootools

Ajax is very important in our front-end development, so let's take a separate lesson. First, let's take a look at the ajax structure of mootools.

Syntax:
Var myRequest = new Request ([parameter]);


Parameters:
Url-(string: null by default) the URL to be requested.
Data-(string: null by default) data to be requested or sent by default.
Link-(string: The default value is 'ignore '.
'Ignore'-when the request is being executed, the new request will be ignored.
'Cancel'-when the request is being executed, the request in progress will be canceled immediately and a new request will be executed.
'Chain'-when the request is being executed, the new request link will be followed by the current request and all requests will be executed in sequence.
Method-(string: Default Value: 'post') HTTP request type, which can be 'post' or 'get '.
Emulation-(boolean: true by default) simulation, usually ignore
Async-(boolean: The default value is true) asynchronous. If it is set to false, browser requests will be frozen synchronously during data request, which is usually ignored.
Timeout-(integer: 0 by default) timeout
Headers-(object) sets the content-type header.
UrlEncoded-(boolean: true by default) url encoding. If it is set to true, the content-type header will be set to www-form-urlencoded + encoding
Encoding-(string: The default value is 'utf-8.
NoCache-(boolean; default value: false) If set to true, no cache
IsSuccess-(function) events after the end of the request.
EvalScripts-(boolean: false by default) if it is set to true, the script in the result will be executed.
EvalResponse-(boolean: false by default) if it is set to true, the request content will be executed.
User-(string: null by default) If this option is set, authentication will be attempted during the request.
Password-(string: null by default) is used with the user. When setting this item, enter a password instead of an asterisk.

All ajax parameters are listed above. What events does mootools provide for us? Let's take a look:

OnRequest
Triggered when the request is sent.

OnLoadstart
Triggered when the request has been loaded before all other processes.

OnProgress
Triggered when the request is creating an upload or download process.

OnComplete
Triggered when the request ends.

OnCancel
Triggered when the request is canceled.

OnSuccess
Triggered when the request is successfully completed.

OnFailure
Triggered when the request fails.

OnException
Triggered when a request header fails to be set.

OnTimeout
This parameter is triggered when the number of milliseconds specified by options. timeout is exceeded, but the status value does not change.

Let's take a look at some additional methods:

SetHeader
Add or modify the header information of a request. options is not overwritten.
Example:
Var myRequest = new Request ({url: 'getdata. php', method: 'get', headers: {'x-request': 'json '}});
MyRequest. setHeader ('Last-modified', 'sat, 1 Jan 2005 05:00:00 gmt ');

GetHeader
Return the response header. null if no response is found.
Example:
Var myRequest = new Request ({url: 'getdata. php', method: 'get', onSuccess: function (responseText, responseXML ){
Alert (this. getHeader ('date'); // display service data (for example, 'thu, 26 Feb 2009 20:26:06 gmt ')
}});

Send
Open the request link and send the preset data in options
Example:
Var myRequest = new Request ({
Url: 'http: // localhost/some_url'
}). Send ('Save = username & name = john ');

Cancel
Cancels a running request.
Example:
Var myRequest = new Request ({url: 'mypage.html ', method: 'get'}). send ('some = data ');
MyRequest. cancel ();

IsRunning
Returns true if the current request is running.
Example:
Var myRequest = new Request ({url: 'mypage.html ', method: 'get'}). send ('some = data ');
If (myRequest. isRunning () // It runs!

As mentioned above, so many examples have not yet been taken into consideration, and even a complete example has not been provided. The ajax of Mootools is powerful enough. I like it. Hey, now, let's go to the topic to show you an example of a complete ajax request:

Var myRequest = new Request ({// create a Request object
Url: 'image. php', // address to be requested
OnProgress: function (event, xhr) {// The creation progress is displayed in the console.
Var loaded = event. loaded, total = event. total;
Console. log (parseInt (loaded/total * 100,10 ));
}
}). Send (); // use its send method to send

// Another example
Var myElement = $ ('myelement'); // select a node
Var myRequest = new Request ({// create a Request object
Url: 'getmytext. php', // address to be requested
Method: 'get', // get request
OnTimeout: function () {// timeout
MyElement. set ('text', 'timeout ');
},
OnFailure: function () {// request failed
MyElement. set ('text', 'request failed ');
},
OnProgress: function (event, xhr) {// The creation progress is displayed in the console.
Var loaded = event. loaded, total = event. total;
Console. log (parseInt (loaded/total * 100,10 ));
},
OnRequest: function () {// set content when a request is sent
MyElement. set ('text', 'loading ...');
},
OnSuccess: function (responseText) {// reset the content after the end
MyElement. set ('text', responseText );
},
OnFailure: function () {// prompt upon failure
MyElement. set ('text', 'Sorry, your request failed :(');
}
});

// $ ('Mylink') triggers the ajax send Method
$ ('Mylink'). addEvent ('click', function (event ){
Event. stop (); // terminate the default event $ ('mylink') (for example, <a ..> to prevent the hyperlink from going to another page)
MyRequest. send ('userid = '+ this. get ('data-userid '));
});

After reading the complete example above, do you feel the ajax of Mootools is tough? Or do you think he is too complicated? It doesn't matter if I come up with a simple model. No matter what your preferences are, you will be satisfied.

Var myHTMLRequest = new Request.HTML().get('myPage.html ');
Var myHTMLRequest = new Request. HTML ({url: 'myPage.html '}). post ('user _ id = 25 & save = true ');

<Div id = "content"> Loading content... </div>
Parameters ('content'{.load('page_1.html ');

// Load "load /? User_id = 25 ".
Var myHTMLRequest = new Request. HTML ({url: 'Load/'}). get ({'user _ id': 25 });

Data from Element via POST:
<Form action = "save/" method = "post" id = "user-form">
<P>
Search: <input type = "text" name = "search"/>
Search in description: <input type = "checkbox" name = "search_description" value = "yes"/>
<Input type = "submit"/>
</P>
</Form>

// Here is a submit event
Var myHTMLRequest = new Request. HTML ({url: 'save/'}). post ($ ('user-form '));

Well, after this lesson is over, join the group (16648471) for discussion if you have any questions. Note: When adding a group, you need to specify the website from which you came.

Related courses:
One week learn Mootools 1.4 Chinese Tutorial: Sequence Theory
One week learn Mootools 1.4 Chinese tutorial :( 1) Dom Selector
One week learn Mootools 1.4 Chinese tutorial :( 2) Functions
One week learn Mootools 1.4 Chinese tutorial :( 3) Events
One week learn Mootools 1.4 Chinese tutorial :( 4) Type
One week learn Mootools 1.4 Chinese tutorial :( 5) Ajax
One week learn Mootools 1.4 Chinese tutorial :( 6) Animation
One week learn Mootools 1.4 Chinese tutorial :( 7) Summary ends

Other articles about Mootools 1.4:
Lightbox effect plug-in I wrote, based on MooTools 1.4
My perpetual calendar plug-in (including calendar, solar term, various holidays, etc.), based on MooTools 1.4
I wrote an effect plug-in similar to the menu in the upper left corner of the home page of this site, based on MooTools 1.4
Advanced usage of delay in Mootools
Bind is used in Mootools to bind objects to functions.
Using extend and implement in Mootools to extend functions or methods for your Functions
Write an extension by yourself and change the syntax of Mootools exactly the same as that of Jquery.
Mootools1.4 custom events
Using Mootools1.4, I wrote something that moves the background image as the mouse moves.

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.