Home > Web Front-end > JS Tutorial > body text

Javascript cross-domain access solution_javascript skills

WBOY
Release: 2016-05-16 18:55:59
Original
926 people have browsed it

There are two types of situations here:
1. Access to pages between subdomains based on the same parent domain; see the following three domain domains: taobao.com, jipiao.taobao.com, promotion.taobao.com; they have the same The parent domain is taobao.com.
2. Access between pages based on different parent domains; see the following three domain domains: taobao.com, baidu.com, sina.com.cn; they have different parent domains.

The solutions to solve the cross-domain problem between them are:
Option 1: Server Proxy
The page JS of domain A needs to access the link under domain B to obtain data , this solution establishes a Proxy program on the server side of domain A (it may be any server program such as ASP, servlet, etc.). The page JS of domain A directly calls the Proxy program under this domain. The proxy program is responsible for sending the request to domain B. link and obtain the data, and finally return the data to the page JS for use through Proxy.
The access process is: JS under domain A --> Proxy under domain A -- > Link under domain B
Example:
Step 1:
Domain A: http://Jipiao.taobao.com/test.htm
javascript script on the page:

Copy code The code is as follows:



Step 2:
Complete the Proxy program of the domain A server (assumed to be a servlet here), the pseudo code is as follows:
Copy code The code is as follows:

Public class Proxy extends….{
..doGet(…… ..){
HttpClient client=……;
GetMethod get=new GetMethod("www.baidu.com/xxxxx.do"); //Access the link to domain B
int statusCode = client. executeMethod(get);
if (statusCode != HttpStatus.SC_OK) {
byte[] responseBody = get.getResponseBody();
String res=new String(responseBody);
Httpresponse.getWriter ().write(res);//Return data to domain A
}
}
}

Option 2: Through Script tag:
in domain A Write an empty Script tag in the head of the page http://Jipiao.taobao.com/test.htm:
Copy code The code is as follows:







Note: This solution requires domain B to be returned The data must be in a legal JSON format or a JS file format; for example, the data format returned by domain B is as follows:
Var remote={test:'hello'};
Var f=[2,1];

Option 3: Hide iframe and share domain:
Write a hidden iframe on the domain A page http://jipiao.taobao.com/yyyy.htm:
Copy code The code is as follows: