Three ways to implement Ajax across domains

Source: Internet
Author: User
Tags ming

Turn

Because of the need to use AJAX to request requests under other domain names at work, there is a case of denial of access because Ajax can only access local resources and not cross-domain access because of security-based considerations.

For example, if your website domain name is aaa.com and you want to request bbb.com content from your domain name via Ajax, the browser will consider it unsafe and therefore deny access.

There are several scenarios for cross-domain issues:

Backstage in Baidu Search solution solution to this problem, summed up a total of three options: Agent, JSONP, XHR2 (XMLHttpRequest Level 2).

The first method of proxy: This is done through the background (ASP, PHP, Java, ASP. NET) to get the content of the other domain name, and then return the content to the front end, so because under the same domain name, so there is no cross-domain problem.

Implementation code: Create an AJAX request (page address: http://localhost/ajax/proxy.html)

    var request = null;    if (window. XMLHttpRequest) {        request = new XMLHttpRequest;    } else{        request = new ActiveXObject ("Microsoft.XMLHTTP");    }    Request.onreadystatechange = function{        console.log (this.readystate);        if (this.readystate===4 && this.status===200) {var resultobj = eval ("(" +this.responsetext+ ")");    Converts the returned text data to the JSON object document.getElementById ("box"). InnerHTML = resultobj.name+ ":" +resultobj.sex;    Display the returned content in the page        }    }    request.open ("POST", "proxy.php", true);    Request.setrequestheader ("Content-type", "application/x-www-form-urlencoded");    Request.send ("Name= Lu Ming-Yin &sex= male");

Create an AJAX request.

proxy.php Code

Header ("Content-type:text/html;charset=utf-8"); $url = "Http://localhost:63342/ajax/proxy.js"; $contents = file_get_ Contents ($url); Echo $contents;

Get the Proxy.js file under localhost:63342 using PHP code.

Proxy.js Code

Proxy.html Running Results

At this point, the use of proxies enables access to files between different domains.

First, the proxy.html uses Ajax to access the proxy.php file in the background, and then proxy.php to access localhost after receiving the request. : 63342 in the Proxy.js file, after getting the contents of the Proxy.js, the content is returned to the front page, which enables cross-domain functionality.

If you want to access multiple cross-domain files, you can tell the background proxy.php file the address of the file you want to access in the form of a parameter.

The second method is JSONP (get requests only): It was later discovered that the JS file was not affected by the cross-domain when it was called, thus deriving the second scenario.

is to load the data into the JS file on the remote server for the client to call and further process.

Jsonp.html

    var url = "Http://localhost:63342/ajax/jsonp.php?name= lu Ming &sex= male &callbackname=jsonp_callback"; Access localhost:63342 under jsonp.php    var scripttag = document.createelement ("script");   Create a script tag    scripttag.setattribute ("src", url);  Set the SRC attribute of script    document.body.appendChild (scripttag);   Add the script tag to body    //callback function    var jsonp_callback = function (resultobj) {        document.getElementById ("box"). InnerHTML = resultobj.name+ ":" +resultobj.sex;    }

jsonp.php

$name = $_get["name"];    $sex = $_get["Sex"];    $callbackname = $_get["Callbackname"];    callback function name    echo "$callbackname ({name: ' $name ', Sex: ' $sex '})";

Jsonp.html Running results:

Implementation principle: Because the use of the script tag calls the remote JS file is not affected by the cross-domain, so you can create a script tag, through the SRC attribute to access the remote file.

This is not Ajax, but it can implement AJAX-like functionality.

The third method XMLHttpRequest Level 2: HTML5 provides XMLHttpRequest level 2 for cross-domain access and other new features

This requires adding the following code on the remote server side

This allows the client to use regular AJAX code.

Summary: The proxy implementation is the most troublesome, but the most widely used, any AJAX-enabled browser can use this way.

JSONP is relatively simple, but it only supports get-mode calls.

XHR2 is the simplest, but only supports HTML5, and if you are developing on the mobile side, you can choose to use XHR2.

Three ways to implement Ajax across domains

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.