Ajax for beginners. ajax for beginners
I. Ajax introduction, advantages and disadvantages, application scenarios and technologies
Ajax introduction:
Asynchronous Javascript And XML (Asynchronous JavaScript And XML)
It is not a single technology, but a combination of a series of interactive web application technologies.
AJAX is a technology used to create fast dynamic web pages. By performing a small amount of data exchange with the server in the background, AJAX can implement asynchronous updates on webpages. This means that you can update a part of a webpage without reloading the entire webpage.
Advantages:
- The page is refreshing and the user experience is good.
- Asynchronous Communication provides faster response.
- Reduces redundant requests and server load
- Based on standardized and widely supported technologies, you do not need to download plug-ins or small programs.
Disadvantages:
- Ajax kills the back button, which destroys the browser's back-up mechanism.
- Security issues exist.
- Weak support for search engines.
- Destroys the program exception mechanism.
- Direct access via URL is unavailable
Ajax application scenarios
- Scenario 1. Data Verification
- Scenario 2. Retrieve data as needed
- Scenario 3. automatically update the page
AJAX contains the following five parts:
Ajax is not a new technology, but a combination of several original technologies. It is composed of the following technologies.
- CSS and XHTML are used for representation.
- Use the DOM model for interaction and dynamic display.
- Data Interchange and operation technology, using XML and XSLT
- Use XMLHttpRequest to perform asynchronous communication with the server.
- Use javascript to bind and call.
In the above technical procedures, apart from XmlHttpRequest objects, all other technologies are based on web standards and have been widely used. Although XMLHttpRequest has not yet been adopted by W3C, but it is already a standard of fact, because almost all mainstream browsers currently support it
The first figure particularly illustrates the structural differences between traditional Web applications and Web applications using AJAX technology.
The main difference is not JavaScript, not HTML/XHTML or CSS. Instead, XMLHttpRequest is used to asynchronously request XML data from the server.
Let's look at the second figure. In the traditional Web application mode, the user experience is separated. Click-> wait-> view the new page-> click-> and then wait. After AJAX technology is adopted, most of the computing work is done by the server without the user's perception.
2. Create ajax
The principle of Ajax is simply to use the XmlHttpRequest object to send asynchronous requests to the server, obtain data from the server, and then use javascript to operate the DOM to update the page. The most critical step is to obtain request data from the server. The native ajax creation can be divided into the following four steps:
1. Create an XMLHttpRequest object
The core of Ajax is the XMLHttpRequest object, which is the key to Ajax implementation. It is used to send asynchronous requests, receive responses, and execute callbacks.
All modern browsers (IE7 +, Firefox, Chrome, Safari, and Opera) have built-in XMLHttpRequest objects.
Syntax for creating an XMLHttpRequest object:
var xhr = new XMLHttpRequest();
Earlier versions of Internet Explorer (IE5 and IE6) Use ActiveX objects:
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
To handle all modern browsers, including IE5 and IE6, check whether the browser supports XMLHttpRequest objects. If yes, create an XMLHttpRequest object. If not, ActiveXObject is created:
Tools and functions compatible with various browsers for creating Ajax
function createRequest (){
try {
xhr = new XMLHttpRequest();
}catch (tryMS){
try {
xhr = new ActiveXObject("Msxm12.XMLHTTP");
} catch (otherMS) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch (failed) {
xhr = null;
}
}
}
return xhr;
}
2. Prepare the request
Initialize the XMLHttpRequest object and accept three parameters:
xhr.open(method,url,async);
The first parameter represents a string of the Request type. Its value can be GET or POST.
GET request:
xhr.open("GET",demo.php?name=tsrot&age=24,true);
POST request:
xhr.open("POST",demo.php,true);
The second parameter is the URL to be sent as the request destination.
The third parameter is true or false, indicating whether the request is sent in asynchronous or synchronous mode. (The default value is true. Generally, false is not recommended)
- False: requests sent in synchronous mode will suspend all javascript code execution until the server gets a response. If the Browser fails to connect to the network or download the file, the page will remain suspended.
- True: when a request is sent in asynchronous mode, the browser can continue to load the page and execute other javascript code while sending and receiving data from the request object.
3. Send a request
xhr.send();
Generally, parameters submitted using Ajax are simple strings. You can directly use the GET method to write the parameters to be submitted to the url parameters of the open method, in this case, the send method parameter is null or null.
GET request:
xhr.open("GET",demo.php?name=tsrot&age=24,true);xhr.send(null);
POST request:
To POST data like an HTML form, usesetRequestHeader()To add an HTTP header. Thensend()The method specifies the data you want to send:
xhr.open("POST",demo.php,true);
xhr.setRequestHeder("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xhr.sen
4. Handling responses
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
}
Onreadystatechange: execute the following function when the processing process changes.
ReadyState: ajax processing process
0: request not initialized (not called yetopen()).
1: The request has been created but has not been sent (no callsend()).
2: The request has been sent and is being processed (the content header can be obtained from the response ).
3: The request is being processed. Generally, some data in the response is available, but the server has not yet completed the response generation.
4: The response has been completed. You can obtain and use the server response.
Status attribute:
- 200: "OK"
- 404: Page not found
ResponseText: Get Response Data in string format
ResponseXML: Get Response Data in XML format
UseJSON.stringify
Use json to convert to object formatJSON.parse()
The returned value is a json string.JSON.parse(xhr.responseText)Convert to JSON object
The data returned from the server is in json format. Here is an example to illustrate how to use
1. First, you need to retrieve data from the XMLHttpRequest object. This is a JSON string and convert it to a real JavaScript Object. UseJSON.parse(xhr.responseText)Convert to JSON object
2. traverse the obtained array and add new elements to the DOM.
function example(responseText){
var saleDiv= document.getElementById("sales");
var sales = JSON.parse(responseText);
for(var i=0;i<sales.length;i++){
var sale = sales[i];
var div = document.createElement("div");
div.setAttribute("class","salseItem");
div.innerHTML = sale.name + sale.sales;
salseDiv.appendChild(div);
}
}
5. Complete example
var xhr = false;
if (XMLHttpRequest) {
xhr = new XMLHttpRequest ();
} else {
xhr = new ActiveXObject ("Microsoft.XMLHTTP");
};
if (xhr) {// If xhr creation fails, or the original false
xhr.open ("GET", "./ data.json", true);
xhr.send ();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log (JSON.parse (xhr.responseText) .name);
}
}
}
Data. json
{
"name":"tsrot",
"age":24
}
This process must be kept in mind.
function ajax (url, success, fail) {
// 1. create a connection
var xhr = null;
xhr = new XMLHttpRequest ()
// 2. Connect to the server
xhr.open ('get', url, true)
// 3. send the request
xhr.send (null);
// 4. accept the request
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
success (xhr.responseText);
} else {// fail
fail && fail (xhr.status);
}
}
}
}
XMLHttpRequest workflow for asynchronous requests for Remote Data
About JSONP
In addition to XMLHttpRequest, you can use JSONP to access the data on the web server.
If both HTML and JavaScript are on the same machine as the data, you can use XMLHttpRequest
What is JSONP?
JSONP (JSON with Padding) is an unofficial protocol that allows the server to integrate Script tags to return to the client, cross-origin access is implemented through javascript callback (this is only a simple implementation form of JSONP)
What is JSONP used?
Due to the restrictions of the same-origin policy, XmlHttpRequest only allows requests to resources of the Current Source (domain name, protocol, Port). To implement cross-origin requests, you can use the script tag to implement cross-origin requests, then the JSON data is output on the server side and the callback function is executed to solve cross-Origin data requests.
How to Use JSONP?
After the client declares the callback function, the client requests data to the server through the script tag, and then the server returns the corresponding data and dynamically executes the callback function.
When XMLHttpRequest is used, we get a string.JSON.parseConverts a string to an object. When jsonp is used, the script flag parses and executes the Returned Code. When we process data, it is already a JavaScript Object.
Simple instance
<meta content = "text / html; charset = utf-8" http-equiv = "Content-Type" />
<script type = "text / javascript">
function jsonpCallback (result) {
alert (result.a);
alert (result.b);
alert (result.c);
for (var i in result) {
alert (i + ":" + result [i]); // Cycle output a: 1, b: 2, etc.
}
}
</ script>
<script type = "text / javascript" src = "http://crossdomain.com/services.php?callback=jsonpCallback"> </ script>
<!-callback parameter indicates the function to use when generating JavaScript code jsonpcallback->
Pay attention to browser cache issues
- Adding a random number at the end can avoid frequent requests to the same link.
- `
Iii. Ajax in jQuery
Ajax encapsulation case in jQuery
// ajax request background data
var btn = document.getElementsByTagName ("input") [0];
btn.onclick = function () {
ajax ((// json format
type: "post",
url: "post.php",
data: "username = poetries & pwd = 123456",
asyn: true,
success: function (data) {
document.write (data);
}
});
}
// Encapsulate ajax
function ajax (aJson) {
var ajx = null;
var type = aJson.type || "get";
var asyn = aJson.asyn || true;
var url = aJson.url; // url receives the transmission position
var success = aJson.success; // success callback function after receiving transmission
var data = aJson.data || ''; // data receive data that needs to be transmitted
if (window.XMLHttpRequest) {// Compatible processing
ajx = new XMLHttpRequest (); // General browser
} else
{
ajx = new ActiveXObject ("Microsoft.XMLHTTP"); // IE6 +
}
if (type == "get" && data)
{
url + = "/?" + data + "&" + Math.random ();
}
// Initialize the ajax request
ajx.open (type, url, asyn);
// Specify the format of the transmitted data
ajx.setRequestHeader ('content-type', 'application / x-www-form-urlencoded');
// Send ajax request (including transmission of post data)
type == "get"? ajx.send (): ajx.send (aJson.data);
// Process the request
ajx.onreadystatechange = function (aJson) {
if (ajx.readState == 4) {
if (ajx.status == 200 && ajx.status <300) // 200 is the status code of a successful HTTP request
{
// The request successfully processed the data
success && success (ajx.responseText);
} else {
alert ("Request error" + ajx.status);
}
}
}
Ajax methods in jQuery
Jquery encapsulates Ajax operations.$.ajax()The method belongs to the bottom layer, and the 2nd layer isload(),$.get(),$.post();Layer 3 is$.getScript(),$.getJSON()The usage frequency of Layer 4 is very high.
Load () method
load()The method is the simplest and most common ajax method in jquery. It can load remote HTML code and insert the DOM structure as follows:load(url,[data],[callback])
Use the url parameter to specify the selector to load certain elements in the page. url Syntax: url selector Note: there is a space between the url and the selector.
Transfer Mode
load()The method is automatically specified based on the parameter data. If no parameter is transmitted, the GET method is used. Otherwise, the POST method is used.
Callback Parameters
The operation that must be performed after the loading is complete. The function has three parameters, which represent the content returned by the request, the Request status, and the XMLHttpRequest object.
The callback function is triggered once the request is complete.
$ ("# testTest"). load ("test.html", function (responseText, textStatus, XMLHttpRequest) {
// respnoseText content returned by the request
// textStatus request status: sucess, error, notmodified, timeout
// XMLHttpRequest
})
Load Method Parameters
Parameter Name |
Type |
Description |
Url |
String |
Request the URL of the HTML page |
Data (optional) |
Object |
Key/value data sent to the server |
Callback (optional) |
Function |
The callback function when the request is complete, whether the request is successful or failed |
$. Get () and $. post () Methods
load()The method is usually used to obtain static data files from the web server. You can use$.get()And$.post()Or$.ajax()Method
Note:$.get()And$.post()The method is the global function in jquery.
$. Get () method
$.get()Method: Use the GET Method for asynchronous requests
Structure:$.get(url,[data],callback,type)
If the Content returned by the server is in xml format, you need to set the Content-Type code on the server side as follows:header("Content-Type:text/xml:charset=utf-8") //php
$. Get () method Parameter Parsing
Parameters |
Type |
Description |
Url |
String |
URL of the Request HTML page |
Data (optional) |
Object |
The key/value data sent to the server will be appended to the request URL as QueryString. |
Callback (optional) |
Function |
A successfully loaded callback function (this method is called only when the returned status of Response is success) |
Type (optional) |
String |
The format of the content returned by the server, including xml, html, script, json, text, and _ default. |
$. Post () method
It corresponds$.get()The method structure and usage are the same, there are the following differences:
- A GET request transmits parameters and a URL, while a POST request sends the object content of an Http message to the web server. In an ajax request, this difference is invisible to users.
- The GET method has a size limit on the data to be transmitted (generally not greater than 2 kb), while the data to be transmitted using the POST method is much larger than the GET method (theoretically unlimited)
- The data requested by the GET method is cached by the browser, so others can read the data from the browser's historical records, such as the account and password. In some cases, the GET method may cause serious security problems, while the POST method can avoid these problems.
- Data transmitted in GET and POST methods is also obtained on the server. In PHP, The GET method is used$_GET[]Get; POST Method$_POST[]Both methods are available.$_REQUEST[]To obtain
Summary
Useload(),$.get()And$.post()Method to complete some common Ajax programs, If you need complex Ajax programs, you need to use$.ajax()Method
$. Ajax () method
$.ajax()The method is jquery's underlying Ajax implementation. Its structure is$.ajax(options)
This method has only one parameter, but this object contains$.ajax()The request settings and callback function required by the method. The parameter exists as key/value, and all parameters are optional.
$. Ajax () method common Parameter Parsing
Parameters |
Type |
Description |
Url |
String |
(The current page address by default) the address for sending the request |
Type |
String |
The request method (POST or GET) is GET by default. |
Timeout |
Number |
Set Request timeout (MS) |
DataType |
String |
Expected type returned by the server. Available types: Xml: the XML document is returned and can be processed by jquery. Html: returns the HTML information of plain text. The script tag is also executed when the DOM is inserted. Script: javascript code that returns plain text. Results are not automatically cached unless cache parameters are set. Note: During remote requests, all POST requests are converted to GET requests. Json: Return JSON data Jsonp: JSONP format. When calling a function in jsonp format, for example, myurl? Call back = ?, Jquery will automatically Replace the last one? For the correct function name to execute the callback function Text: returns a plain text string. |
BeforeSend |
Function |
Before sending a request, you can modify the function of the XMLHttpRequest object, for example, adding a custom HTTP header. In beforeSend, if false is returned, the Ajax request can be canceled. The XMLHttpRequest object is a unique parameter. Function (XMLHttpRequest ){ This; // The options parameter passed when calling this Ajax request } |
Complete |
Function |
Callback Function after the request is completed (called when the request succeeds or fails) Parameter: XMLHttpRequest object and a string describing the successful request type Function (XMLHttpRequest, textStatus ){ This; // The options parameter passed when calling this Ajax request } |
Success |
Function |
The callback function called after the request is successful. There are two parameters. (1) data returned by the server and processed according to the dataTyppe Parameter (2) A string describing the status Function (data, textStatus ){ // Data may be xmlDoc, ''jsonobj, html, text, etc. This; // The options parameter passed when calling this Ajax request } |
Error |
Function |
Function called when the request fails |
Global |
Boolean |
The default value is true. Indicates whether to trigger a global Ajax event. setting this parameter to false will not trigger the event. AjaxStart or AjaxStop can be used to control various Ajax events. |
Reference
Sharp jQuery
Summary
The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.