Ajax Learning Full Set (most complete classics) _ajax related

Source: Internet
Author: User
Tags http authentication http post prefetch script tag domain transfer ssl certificate

Introduction to Ajax

Ajax, "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), refers to a web development technology that creates interactive Web applications. Ajax is not a new programming language, but a new way of using existing standards. Ajax can exchange data with the server without reloading the entire page. This kind of asynchronous interaction allows the user to click and get new data without refreshing the page. With Ajax, users can create a direct, highly available, richer, more dynamic Web user interface that is 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 manipulation

• Asynchronous data reception using XMLHttpRequest

Use Ajax to do:

• When registering, enter the user name to automatically detect if the user already exists.

* When landing, prompt username password error

• Delete data rows, send row IDs to the background, delete the background in the database, and delete the data rows in the page DOM after the database has been deleted successfully.

Ajax forgery

The IFRAME is our commonly used IFRAME tag:<iframe>. IFRAME tags are a form of the framework, but also more commonly used, the IFRAME is usually included in other pages, such as we can load on our own site pages of other people's websites or other pages of the content of the site. The biggest function of the IFRAME tag is to make the page look beautiful. There are many uses of the IFRAME tag, the main difference being the form of the IFRAME label definition, such as the definition of the length and width of the IFRAME.

Therefore, the IFRAME tag has the feature of locally loaded content, so it can be used to forge AJAX requests.

<! DOCTYPE html>  

The principle is this, set a Submit button, and then set an input box, when we enter a URL, in the current page load input URL page information, presented in the IFrame box, so you can do not refresh the URL to submit different information.

Native Ajax

The core of Ajax is the XMLHttpRequest object (XHR). XHR provides an interface for sending requests to the server and for analyzing the server response. Ability to get new data from the server asynchronously.

One, XMLHttpRequest object

The core of Ajax is the XMLHttpRequest object (XHR). XHR provides an interface for sending requests to the server and for analyzing the server response. Ability to get new data from the server asynchronously.

The main methods of XHR are:

1. Void open (String method,string url,boolen async)  
 is used to create request  
  Parameters:
    Method: Request (String type), such as: POST, GET, DELETE ...
    URL:  Address to request (string type)
    Async: Asynchronous (Boolean type)
2. void Send (string body)
  to send request
  parameters: Body
    : The data to send (String type)
3. void setRequestHeader (string header,string value) is
  used to set the request header
  parameter:
    header: Key (String type) Vlaue of the request header
    : value of the request header (string type)
4. String getAllResponseHeaders ()
  gets all response header
  return values:
    response header data (string type)
5. String getResponseHeader (string header)
  gets the value parameter of the header specified in the response header:
    Header: The key (String type) return value of the response header
  :
    the value
of the header specified in the response header 6. void abort () 

termination request

The main properties of XHR are:

1. Number ReadyState
  state value (integer) that determines the current active phase of the request/response process • 0: uninitialized. Open () method not invoked
 • 1: Started. The open () method has been called without calling Send () method
 • 2: Send. The Send () method has been called and no response received
 3: Receive. A partial data has been received
 • 4: Completed. You have received all the data and you can use 2 on the client
 . function onreadystatechange        
 automatically triggers execution of its corresponding functions (callback function) 3 when the value of readystate changes 
 . String ResponseText            
 The text (string type) that is returned as the response body
 4. XmlDocument          
 The data returned by the Responsexml server (XML object) 
 5. Number States  
 Status code (integer), such as: 200, 404 ... 6. String Statestext             
 status text (string), such as: OK, NotFound ...

Second, GET request

Get is used to query certain information to the server:

<! DOCTYPE html>  

Third, POST request

Post requests are used to send data to the server that should be saved. The body of a POST request can contain very much data, and the format is not limited.

<! DOCTYPE html>  

jquery Ajax

JQuery provides a number of AJAX-related methods.

With the JQuery AJAX approach, you can use HTTP GET and HTTP Post to request text, HTML, XML, or JSON from a remote server-and you can load the external data directly into the selected elements of the Web page.

jquery is not a producer, but a nature porter.

jquery ajax essence XMLHttpRequest or ActiveXObject

Note: The 2.+ version no longer supports browsers below IE9

1. Jquery.get (...)
     All parameters: url: URL of the page to be loaded: Key/value parameter to be sent.
     Success: callback function when load succeeds.
    DataType: Returns the content format, XML, JSON, script, text, HTML 2.jquery.post (...) All parameters: url: URL of the page to be loaded: Key/value parameter success: callback function DataType when load succeeds: Return content format, XML, JSON, scrip
    T, text, HTML 3.jquery.getjson (...)
     All parameters: url: URL of the page to be loaded: Key/value parameter to be sent.
Success: callback function when load succeeds.
    4.jquery.getscript (...)
     All parameters: url: URL of the page to be loaded: Key/value parameter to be sent.
Success: callback function when load succeeds.
    5.jquery.ajax (...) Partial parameters: URL: Request Address type: Request mode, GET, POST (1.9.0) Headers: request header data: ContentType to send information to The content encoding type of the server (default: "application/x-www-form-urlencoded;
     Charset=utf-8 ") Async: Asynchronous timeout: Set request timeout (milliseconds) Beforesend: function (global) to execute before sending request complete: callback function executed after completion (global) Success: Callback function (global) error after success: callback function (global) executed after failure accepts: sent to the server by request hair, telling the server the data type accepted by the current client class DataType: Data returned from the server side
     Convert to specified type XML: Converts server-side returned content to XML format "text": Converts server-side returned content to normal text format "HTML": Converts server-side returned content to normal text format, when inserted into the DOM, if the JavaScript tag is included,
     Will try to execute it.  Script: Attempts to execute the return value as JavaScript, and then converts the server-side returned content to the normal text format "JSON": Converts server-side returned content to the appropriate JavaScript object "JSONP": Jsonp format using JSONP when calling a function, such as "myurl?callback=?" JQuery will automatically replace? To the correct function name to execute the callback function

Write one of the simplest examples:

<! DOCTYPE html>
 
 

Cross-Domain Ajax

Because the browser has a homology policy mechanism, the homology policy prevents documents or scripts loaded from one source from getting or setting the properties of a document loaded by another source. So Ajax itself is not cross-domain, by generating a script tag to implement Cross-domain. Because the SRC attribute of the script label is not a cross-domain restriction.

Browser homology policies are not restricted to all requests:

• Restrictions: XMLHttpRequest

• No restrictions: IMG, iframe, script and so on with SRC attributes of the label

Note: I simulate cross-domain, need to add two domain name in the host file of our own computer now, I add here is zhangyanlin.com and aylin.com these two domain names

One, JSONP implementation of cross domain requests

JSONP is an unofficial protocol that allows the integration of script tags on the server side back to the client, enabling Cross-domain access through JavaScript callback. JSONP only cross domain requests via get mode

<! DOCTYPE html>  

aylin.com domain name This side can give the definition function

#
class Indexhandler (Tornado.web.RequestHandler) using the Pythontornado framework: def get
  (self):
    self.write (' Func ([11,22,33]);
  Def post (self, *args, **kwargs):
    self.write (' T2.post ')

In this case, the JSONP uses the SRC of the script label to cross domain requests.

Second, CORS

The above approach, when the browser's homology policy causes Ajax to fail to cross domain transmission, is a way to break through the browser restrictions for transmission. When the data sent to the other side of the domain name, the other party has received, but in return by the browser to block, we can write a string similar to the ID card, through the browser's pre-test, so as to achieve data transmission.

This is divided into simple and not simple requests

Conditions:
  1, Request way: Head, GET, POST
  2, request header information:
    Accept
    accept-language
    content-language
    Last-event-id
    Content-type corresponds to a value of any of the following three
                application/x-www-form-urlencoded
                multipart/form-data
                Text/plain
Note: When the above two conditions are met, it is a simple request, otherwise a complex request

A simple request is one request at a time, and a complex request is a two-time request, which sends a request for a "pre-check" before sending the data, and only the "prefetch" passes before sending another request for data transfer.

Implement AJAX requests based on Cors:

1, support Cross-domain, simple request

Server Settings response header: Access-control-allow-origin = ' domain name ' 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 Cross-domain, complex request

Because of a complex request, a "pre-check" request is sent first, and true data is sent if the pre-test succeeds.

• When a "prefetch" request is requested, the server settings response header is required for the requested mode: Access-control-request-method

• When a "pre-check" request is requested, the server is required to set the response header for the request header: Access-control-request-headers

• "Pre-check" cache time, Server settings 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-domain transfer of cookies

In Cross-domain requests, by default, the HTTP authentication information, the cookie header, and the user's SSL certificate are not sent either in the prefetch request or in the actual request.

If you want to send:

• Browser-side: XMLHttpRequest Withcredentials is True

• Server-side: Access-control-allow-credentials is True

• Note: server-side response Access-control-allow-origin cannot be 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 small set of Ajax to introduce you to learn a full suite (most of the most classic) of all the narrative, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.