A full set of Ajax Learning (the most comprehensive and classic) and the full set of ajax Learning

Source: Internet
Author: User
Tags http authentication ssl certificate

A full set of Ajax Learning (the most comprehensive and classic) and the full set of ajax Learning

Ajax Introduction

AJAX is "Asynchronous Javascript And XML" (Asynchronous JavaScript And XML), which is a Web page development technology used to create interactive web applications. Ajax is not a new programming language, but a new method that uses existing standards. AJAX can exchange data with the server without reloading the entire page. This Asynchronous interaction method allows users to obtain new data without refreshing the page after clicking. With Ajax, users can create direct, highly available, richer, and more dynamic Web user interfaces close to local desktop applications.

Ajax includes:

• XHTML and CSS

• Use the Document Object Model for Dynamic Display and Interaction

• Use XML and XSLT for Data Interaction and operations

• Use XMLHttpRequest for asynchronous data receiving

AJAX can be used:

• When registering, enter the user name to automatically check whether the user already exists.

• A user name and password error is prompted during login

• When deleting a data row, the row ID is sent to the background, and the background is deleted from the database. After the database is deleted successfully, the data row is also deleted in the page DOM.

Ajax forgery

Iframe is a common iframe label: <iframe>. Iframe labels are common in frameworks. iframe is generally used to contain other pages. For example, we can load the content of other websites or other pages on our own websites. The iframe tag is used to make the page look beautiful. Iframe labels are used in many ways. The main difference is that the formats of iframe labels are different. For example, the length, width, and height of iframe are defined.

Therefore, iframe labels have the ability to locally load content, so they can be used to forge Ajax requests.

<! DOCTYPE html> 

The principle is as follows: Set a submit button and an input box. When we enter a URL, load the page information of the entered URL on the current page and display it in the iframe box, in this way, different information can be submitted without refreshing the URL.

Native ajax

The core of Ajax is the XMLHttpRequest object (XHR ). XHR provides interfaces for sending requests to the server and parsing server responses. It can obtain new data from the server asynchronously.

I. XMLHttpRequest object

The core of Ajax is the XMLHttpRequest object (XHR ). XHR provides interfaces for sending requests to the server and parsing server responses. It can obtain new data from the server asynchronously.

XHR methods include:

1. void open (String method, String url, Boolen async) is used to create request parameters: method: Request method (String type), such as POST, GET, DELETE... url: the address to be requested (string type) async: asynchronous or not (Boolean Type) 2. void send (String body) is used to send request parameters: body: data to be sent (String type) 3. void setRequestHeader (String header, String value) is used to set the request header parameter: header: key of the Request header (String type) vlaue: value of the Request header (String type) 4. string getAllResponseHeaders () Get all response header return values: response header data (String type) 5. string getResponseHeader (String header) obtains the value of the specified header in the Response header. Parameter: header: key of the Response header (String type) returned value: the value of the specified header in the Response header 6. void abort () Termination request

XHR has the following attributes:

1. Number readyState status value (integer) to determine the current active phase of the Request/response process • 0: not initialized. Open () method not called • 1: Start. The open () method has been called and the send () method is not called. • 2: send. The send () method has been called and the response is not received. • 3: receive. Some data has been received. • 4: complete. All data has been received. You can use it on the client. function onreadystatechange: when the value of readyState changes, the corresponding Function (callback Function) is automatically triggered. 3. string responseText is the text (String type) returned by the response body. 4. data returned by the XmlDocument responseXML server (Xml Object) 5. number states status code (integer), for example: 200, 404... 6. string statesText status text (String), such as: OK, NotFound...

2. get request

GET is used to query certain information from the server:

<! DOCTYPE html> 

Iii. post requests

The post request is used to send data that should be saved to the server. The body of a POST request can contain a large amount of data and the format is not limited.

<! DOCTYPE html> 

Jquery ajax

JQuery provides multiple AJAX-related methods.

Using the jQuery AJAX method, you can use HTTP Get and HTTP Post to request text, HTML, XML, or JSON from a remote server. At the same time, you can directly load the external data into the selected elements of a webpage.

• JQuery is not a producer, but a nature Porter.

• JQuery Ajax: XMLHttpRequest or ActiveXObject

Note: versions 2. + no longer support browsers earlier than IE9

1. All parameters of jQuery. get (...): url: URL address of the page to be loaded data: Key/value parameter to be sent. Success: callback function when loading is successful. DataType: returned content format, xml, json, script, text, html2.jQuery. post (...) all parameters: url: URL address of the page to be loaded data: Key/value to be sent success: callback function dataType: returned content format, xml, json, script, text, html3.jQuery. getJSON (...) all parameters: url: URL address of the page to be loaded data: Key/value parameters to be sent. Success: callback function when loading is successful. 4. All parameters of jQuery. getScript (...): url: URL address of the page to be loaded data: Key/value parameter to be sent. Success: callback function when loading is successful. 5. jQuery. ajax (...) some parameters: url: request address type: Request method, GET, POST (Use method after 1.9.0) headers: request header data: data to be sent contentType: content Encoding type (default: "application/x-www-form-urlencoded; charset = UTF-8") async: asynchronous timeout: set the request timeout time (millisecond) beforeSend: The function executed before sending the request (global) complete: the callback function executed after completion (global) success: the callback function executed after successful (global) error: the callback function (global) accepts executed after the failure: sends the request hair to the server, telling the server the Data Type dataType accepted by the current client class: convert the data returned by the server to the specified type "xml": Convert the content returned by the server to the xml format" Text: Convert the content returned by the server to the normal text format "html": Convert the content returned by the server to the normal text format. when inserting the DOM, if the JavaScript tag is included, then it will try to execute. "Script": Try to execute the returned value as JavaScript, and then convert the content returned by the server to the common text format "json ": convert the content returned by the server to the corresponding JavaScript Object "jsonp": when calling a function in JSONP format, such as "myurl? Callback =? "Will jQuery be replaced automatically? For the correct function name to execute the callback function

Write a simple example:

<! DOCTYPE html> 

Cross-origin ajax

Because the browser has the same-origin policy mechanism, the same-origin policy prevents you from retrieving or setting attributes of documents loaded from one source. Therefore, ajax itself cannot cross-origin, and cross-origin is implemented by generating a script tag. Because the src attribute of the script tag has no cross-origin restrictions.

Browser same-origin policies do not restrict all requests:

• Constraint: XmlHttpRequest

• Unrestricted: img, iframe, script, and other labels with src attributes

Note: You need to add two domain names in the host file of your computer to simulate cross-origin. Here I add the zhangyanlin.com and aylin.com domain names.

I. JSONP implements cross-origin requests

JSONP is an unofficial protocol that allows the server to integrate Script tags to return to the client and implement cross-origin access through javascript callback. Jsonp can only perform cross-origin requests through get

<! DOCTYPE html> 

The aylin.com domain name can be used to define functions.

# Class IndexHandler (tornado. web. requestHandler): def get (self): self. write ('func ([11,22, 33]); ') def post (self, * args, ** kwargs): self. write ('t2. post ')

Here, jsonp uses the script label src for cross-origin requests.

Ii. CORS

The above method mentioned the same origin policy of the browser, which makes ajax unable to perform cross-origin transmission. Therefore, this method can be transferred without the browser restrictions. When the data is sent to the domain name of the other party, the other party has received the data, but the returned data is blocked by the browser. we can write a string similar to the ID card and pre-check it through the browser, to achieve data transmission.

Simple requests and non-simple requests

Condition: 1. Request Method: HEAD, GET, POST 2. Request Header Information: the value of Accept-Language Content-Language Last-Event-ID Content-Type corresponds to any of the following three application/x-www-form-urlencoded multipart/form-data text /plain note: when both of the preceding conditions are met, the request is a simple request. Otherwise, the request is a complex request.

A simple request is only one request, while a complex request is two requests. A request is sent for "pre-check" before data is sent ", A request is sent for data transmission only after the pre-check is passed.

AJAX requests based on cors:

1. Supports cross-origin and simple requests

The server sets the response header: Access-Control-Allow-Origin = 'domain' or '*'

<!DOCTYPE html>
class MainHandler(tornado.web.RequestHandler):  def get(self):    self.set_header('Access-Control-Allow-Origin', "http://www.xxx.com")    self.write('{"status": true, "data": "seven"}')

2. Support for cross-origin and complex requests

For complex requests, a "pre-check" request is sent first. If the "pre-check" request is successful, real data is sent.

• For a "pre-check" Request, the server must set the response header: Access-Control-Request-Method

• For a pre-check Request, the server must set the response header: Access-Control-Request-Headers.

• Pre-check cache time. The server sets the response header: Access-Control-Max-Age.

<!DOCTYPE html>
class MainHandler(tornado.web.RequestHandler):  def put(self):    self.set_header('Access-Control-Allow-Origin', "http://www.xxx.com")    self.write('{"status": true, "data": "seven"}')  def options(self, *args, **kwargs):    self.set_header('Access-Control-Allow-Origin', "http://www.xxx.com")    self.set_header('Access-Control-Allow-Headers', "k1,k2")    self.set_header('Access-Control-Allow-Methods', "PUT,DELETE")    self.set_header('Access-Control-Max-Age', 10)

3. Cross-origin transmission cookie

By default, HTTP Authentication information, Cookie header, and your SSL certificate are not sent in the pre-check request or in the actual request.

If you want to send:

• Browser: The withCredentials value of XMLHttpRequest is true.

• Server: the value of Access-Control-Allow-Credentials is true.

• Note: the Access-Control-Allow-Origin of the server response cannot be a wildcard *

<!DOCTYPE html>
class MainHandler(tornado.web.RequestHandler):  def put(self):    self.set_header('Access-Control-Allow-Origin', "http://www.xxx.com")    self.set_header('Access-Control-Allow-Credentials', "true")    self.set_header('xxoo', "seven")    self.set_header('zhangyanlinhenshuai', "feichangshuai")    self.set_header('Access-Control-Expose-Headers', "shuai,shuaishuai")    self.set_cookie('kkkkk', 'vvvvv');    self.write('{"status": true, "data": "seven"}')  def options(self, *args, **kwargs):    self.set_header('Access-Control-Allow-Origin', "http://www.xxx.com")    self.set_header('Access-Control-Allow-Headers', "k1,k2")    self.set_header('Access-Control-Allow-Methods', "PUT,DELETE")    self.set_header('Access-Control-Max-Age', 10)

The above is a full set of Ajax Learning (the most comprehensive and classic) Descriptions introduced by the editor. I hope it will be helpful to you. If you have any questions, please leave a message for me, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

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.