In-depth analysis of Ajax and cross-origin issues, and ajax cross-origin resolution

Source: Internet
Author: User

In-depth analysis of Ajax and cross-origin issues, and ajax cross-origin resolution

What Is ajax?

Ajax (Asynchronous JavaScript and XML) is a technology that can request additional data from the server without refreshing pages. The emergence of ajax brings a better user experience.

The core of Ajax is the XMLHttpRequest (XHR) object. XHR provides a smooth interface for sending requests to the server and parsing server responses. you can use the XHR object to obtain new data and insert new data to the page through DOM. although the name contains XML, ajax communication has nothing to do with the data format. This technology can obtain data from the server without refreshing, but not necessarily XML data or json.

XMLHttpRequest object

XHR usage

1. Create an XMLHttpRequest object

2. Send a request

1). Set Request Line xhr. open ()
2) For a POST request, you need to set the Content-Type value of the Request Header xhr. setRequestHeader () POST request header: application/x-www-form-urlencoded
3) set the Request body xhr. send () get request to pass null, post based on the situation

3. Process Server Response

First, determine whether the response status code and asynchronous object have been parsed.

Status Code returned by the server

1xx: Message
2xx: Successful
3xx: Redirection
4xx: Request Error
5xx: Server Error

Status Code readystate of the asynchronous object

0: the asynchronous object has been created.
1: asynchronous object initialization is complete, send a request
2: receive raw data from the server
3: The data is being parsed. It takes time to parse the data.
4: data parsing is complete, and the data can be used

XML

The characteristics of XML, developed by W3C, are data formats that have been strongly recommended by Microsoft and IBM. XML refers to the Extensible Markup Language, which is designed to transmit and store data. HTML is designed to represent pages.

Syntax Rules: similar to HTML, they are all represented by tags.

Special symbols: for example, to use entity-Transfer Character

Xml parsing requires the combination of the front and back ends:
1. When the background returns, set the Content-Type value to application/xml in the response header.
2. When receiving background data from the foreground asynchronous object, remember to receive it in xml format. xhr. responseXML, And it returns an object with the content # document

JSON

JSON (JavaScript Object Notation) is a subset of Javascript and is used to describe the data format. JSON itself is a special string that can be converted to js objects. JSON is one of the most widely used data formats for data transmission over the network.

Syntax Rules:The data is represented by key/value pairs. The data is separated by commas, and the braces save objects. The brackets save arrays. The names and values must be enclosed in double quotation marks (this is a small difference from js ).
Parse/operate JSON in js:
1. JSON. parse (json string); parses a json string into a js object
2. JSON. stringify (js object); convert a js object into a json string

Encapsulate an ajax

Function pinjieData (obj) {// obj is equivalent to {key: value, key: value} // The string finally spliced into a key-value Pair "key: value, key: value "var finalData =" "; for (key in obj) {finalData + = key +" = "+ obj [key] +" & "; // key: value, key: value &} return finalData. slice (0,-1); // key: value, key: value} function ajax (obj) {var url = obj. url; var method = obj. method. toLowerCase (); var success = obj. success; var finalData = pinjieData (obj. data); // finalData Effect key: value, key: value // 1. create xhr object var xhr = new XMLHttpRequest (); // get method splicing address, xhr. send (null) if (method = 'get') {url = url + "? "+ FinalData; finalData = null;} // 2. set Request Line xhr. open (method, url); // if it is a post request, you need to set the request header if (method = 'post') {xhr. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded")} // 3. send xhr. send (finalData); // 4. listen to the data returned by the server xhr. onreadystatechange = function () {if (xhr. status = 200 & xhr. readyState = 4) {var result = null; // obtain the returned data type var rType = xhr. getResponseHeader ("Content-Type"); if (rType. ind ExOf ('xml ')! =-1) {result = xhr. responseXML;} else if (rType. indexOf ('json ')! =-1) {// JSON. parse means to convert a json string // such as [{"src ":". /images/nav0.png "," content ":" item category 1 "}] // convert to js object result = JSON. parse (xhr. responseText);} else {// process result = xhr as a normal string. responseText;} // hand the parsed data to the page to render success (result );}}}

Use ajax in jQueryAPI jQuery ajax

JQuery provides us with more convenient ajax encapsulation.

$. Ajax ({}) can be configured to initiate ajax requests
$. Get () initiates ajax requests in get Mode
$. Post () initiates ajax requests in post Mode
$ ('Form'). serialize () serialized form (formatting key = val $ key = val)

Parameter description

Url: interface address
Type: Request Method (get/post)
Timeout: a parameter of the Number type is required. Set the request timeout time (MS)
DataType: the client should pass a value to the server to tell the server how to handle it:
Data: Send request data
BeforeSend: a parameter of the Function type. 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.
Success: called after a successful response
Error: called when error response occurs
Complete: Call upon response completion (including Success and Failure)

// Ajax === get $. ajax ({url: '', data: 'key = value & key = value', type: 'get', success: function (result) {console. log (result) ;}}); // ajax === post $. ajax ({url: '', data: 'key = value & key = value', type: 'post', success: function (result) {console. log (result) ;}}); // $. get $. get ({url: '', data: 'key = value & key = value', success: function (result) {console. log (result) ;}}); // $. post $. post ({url: '', data: 'key = value & key = value', success: function (result) {console. log (result) ;}}); // when sending a request using ajax in jQuery, you only need to write jsonp in dataType to implement the cross-origin request ype of ajax: 'jsonp'

Cross-Origin

XHR is a major limitation for ajax communication (the same domain, the same port, and the same protocol). It comes from a cross-server security policy. By default, XHR can only request resources in the same domain, this is to prevent some malicious behaviors.

CORS

CORS (cross-origin resource sharing) defines how browsers and servers communicate across domains. CORS allows network applications in one domain to submit cross-origin AJAX requests to another domain. This function is very simple. You only need to send a response header by the server.
CORS supports all types of HTTP requests.
The server supports CORS mainly by setting Access-Control-Allow-Origin.

JSONP

JSONP consists of callback functions and data. JSONP only supports GET requests. The advantage of JSONP is that it supports older browsers and can request data from websites that do not support CORS.
JSONP is used by dynamic <script> elements. The src attribute knows a cross-origin URL. JSONP is a valid JavaScript code, and the browser can request JS files across domains.
Advantages: it is easy to use and can directly access the response text, supporting two-way communication between the browser and the server.
Disadvantages: 1. JSONP loads code from other domains for execution, and there is an insecure risk. 2. It is difficult to determine whether the JSONP request is successful or not.

Cross-subdomain by modifying document. domain

Use window. name for cross-Origin

The window. postMessage method is introduced in html5.

Flash

Iframe

Server setting proxy page

Image Ping

By using tags, a webpage can load images from any webpage.
Image Ping is often used to track the number of user clicks on pages or dynamic ad exposures.

Two disadvantages: 1. Only GET requests are supported. 2. The response text of the server cannot be accessed. It can only be used for individual communications between the browser and the server.

var img = new Image();img.onload = img.onerror = function (){alert("Done!");};img.src = "";

Comet

A more advanced ajax technology. ajax is the technology that requests data from pages to servers. comet is the technology that the server pushes data to pages.

SSE (Server-Sent Events) Server sends Events

Web Sockets

The goal of Web Sockets is to provide full-duplex and bidirectional communication on a single persistent link.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.