Java combined with jquery to achieve data acquisition across domains _java

Source: Internet
Author: User
Tags script tag

One, what is a cross-domain?

Because of the security concerns of browsers, the use of the same source policy limits makes it impossible for jquery to manipulate objects or data directly across domain names. For example: Under the a.com domain name

The a.html page uses jquery to not manipulate the object or data of the b.html page under B.Com domain name, and by default it cannot manipulate the

A Test.html object or data. jquery will be considered a cross domain name as long as the following conditions are met:

1. Primary domains are the same, subdomains are different, such as xxx.aaa.com and yyy.aaa.com

2. Domain name is the same, port is different, such as xxx.aaa.com:8000 and xxx.aaa.com

3. Same domain name, different protocol, such as http://www.aaa.com/and https://www.aaa.com/

Only the protocol, domain name, port three are exactly the same jquery will be considered not cross domain.

Second, the solution of jquery cross-domain operation of the object method

1, top-level domain one to the situation

By default, the A.html page under the a.com domain name uses jquery to not manipulate test.html objects or data under the test.a.com domain name. But for this top-level domain name the same situation as long as in a.html and test.html reset document.domain=a.com can.

2, the top-level domain name is not different to the situation

For the a.html page under the a.com domain name, there are two ways to use jquery to manipulate the data in the b.html page under B.Com domain name $.getjson, $.ajax

(1) through jquery Ajax to cross domain, this is actually adopted in the JSONP way to achieve.

JSONP is an abbreviation of the English JSON with padding. It allows script tags to be generated on the server side to be returned to the client, that is, dynamically generating JavaScript tags,

Data reading is achieved through JavaScript callback.

HTML page End Sample code:

The code is as follows:

 First you introduce jquery's JS package 
 jquery (document). Ready (function () { 

   $.ajax ({

     type: ' Get '),//jquey is not supported for

     post-mode Cross-domain Async:false,

     URL: "Http://api.jb51.net/apitools/ajax_props.do",//cross domain request URL

     dataType: "Jsonp",

     // Passed to the request handler to obtain the parameter name of the JSONP callback function name (default: Callback)

     JSONP: "Jsoncallback",

     //Custom JSONP callback function name,

     success:function (JSON) { 

       alert (JSON); 

     } 

   }); 

 

Server-side sample code, with Java as an example:

Server-side code, is the focus, beginning to think, as long as the client through the JSONP can be directly across the domain access, in fact, the need for server-side support to do.

The code is as follows:

 public void Jsonptest () throws ioexception{

   httpservletrequest request = Servletactioncontext.getrequest ();

   HttpServletResponse response = Servletactioncontext.getresponse ();

   Gets the name of the callback function//callbackname the value of the JSONP callback function, based on the name of the parameter of the HTML specified,

   is actually: success_jsonpcallback

   String callbackname = ( String) Request.getattribute ("Jsoncallback");

   Simply simulate a JSON string, you can actually use Google's Gson for conversion, the number of times through string concatenation

   //{"name": "John", "Age": "

   //\ is the" "Number to escape

   string Jsonstr = "{\ name\": \ "john \", \ "age\": "}";

   The final data returned is: Success_jsonpcallback ({"Name": "John", "Age":})

   String renderstr = callbackname+ "(" +jsonstr+ ");

   Response.setcontenttype ("Text/plain;charset=utf-8");

   Response.getwriter (). write (RENDERSTR); 

 

The principle of Jsonp:

First register a callback (such as ' Jsoncallback ') on the client, and then pass the callback's name (such as: Success_jsonpcallback) to the corresponding handler function on the server side.

The server is a JSON data that needs to be returned to the client. Then, a function is generated in JavaScript syntax, the function name is the value (success_jsonpcallback) of the parameter passed up (Jsoncallback).

Finally, the JSON data is placed into function directly in the form of a parameter, which generates a document of JS syntax and returns it to the client.

The client browser, parsing the script tag, and returning the server-side data as an argument,

Passed into the client's predefined callback function (as in the previous example, the jquery $.ajax () method encapsulates success:function (JSON)).

In fact, Cross-domain is loading data by dynamically increasing the script, and you cannot get the data directly, so you need to use a callback function.

(2) using jquery Getjson to read data across domains

In fact, the fundamental principle of the getjson approach is the same as the way Ajax uses JSONP.

The common Getjson in jquery is called to fetch the remote data and return it in JSON format. The prototype of the function is as follows:

Jquery.getjson (Url,data,success (DATA,STATUS,XHR))

Parameter description

URL required. Specify which URL to send the request to.

Data is optional. Specify the data to be sent to the server along with the request.

Success (DATA,STATUS,XHR) is optional. A function that is required to run when a request succeeds.

Additional parameters:

response-Contains the result data from the request

status-Contains the status of the request

XHR-Contains XMLHttpRequest objects 

This function is shorthand for AJAX functions and is actually equivalent to:

The code is as follows:

$.ajax ({

 url:url,

 data:data,

 success:callback,

 Datatype:json

});

To get to the bottom of this, let's look at how to use Getjson to fetch data across domains.

HTML Page Sample code:

The code is as follows:

$.getjson ("http://api.jb51.net/apitools/ajax_props.do&jsoncallback=?",

  function (data) {

    alert ( data);


Principle of execution:

Send a request to pass a callback callback function name to the server side, the server to get the callback function name, and then return the data in the form of parameters back to the client, so that the client can be transferred to.

So the URL to send the request after the address must be jsoncallback=? Such a parameter, jquery will automatically replace the number with the name of the automatically generated callback function.

So the final actual request is: http://api.jb51.net/apitools/ajax_props.do&jsoncallback=jsonp1322444422697

So the Ajax way to compare, that is, the callback function is an automatically generated function name, one is manually specified function name.
Note the following points:

1. Must be added callback= after the address sent to the data receiver? Such parameters, and this is the name that will be automatically replaced by jquery with the callback method. (You can specify the name of the callback method yourself in Jquery1.4)

2. Note that the JS script sent data can not be written as Var data= "{' username ': ' Sanjer ', ' userid ': ' 110 '}", but to write Var data={username: ' Sanjer ', UserID: ' 110 '}, this should be noted. To receive the data returned by the server side, the server-side package data must be the JSON format string and returned with the callback value. (Take a closer look at the example code above).

3. As a result of invoking jquery's $.getjson method, jquery has its own processing, which is actually requested through the script's SCR, but it is determined that the data is eventually sent out via a get way after the URL, The amount of data sent can not be too much, otherwise the URL will be too long to receive the failure (Getjson method is not possible to post the way submitted).

If you want to send a large amount of data across the domain to use the Ajax method provided by jquery, it is best not to choose the Getjson method.

4. The above examples are based on the premise that you are in control of both aspects of development. Also note that the server program side of the safety factor is not high (recommended data receiver side do not put important, sensitive logical processing unit).

The above Java combined with jquery to achieve cross-domain access to data is a small series of all the content to share, I hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.