jquery Ajax and Getjson The implementation method of capturing JSON data across domains

Source: Internet
Author: User
Tags html page json script tag domain server
Many developers are using jquery for data interaction between the front end and the server side, so it is easy to think that using jquery in the front end can read the data of any site. In the recent development, because of the need to share data with a project of a third-party company, because it does not take up the resources of the server, it was decided to read the data directly in html instead of going through the server-side transfer. Then I just encountered the problem of cross-domain access on the browser side.

Cross-domain security restrictions are all referred to the browser side, there is no cross-domain security restrictions on the server side.

There are currently two methods commonly used for cross-domain access on the browser side:

1. Cross-domain through jQuery's ajax, this is actually achieved using the jsonp method.

jsonp is the abbreviation of json with padding in English. It allows script tags to be generated on the server side and returned to the client, that is, dynamically generated javascript tags, and data can be read in the form of javascript callback.

 

Sample code for html page:

01 // First of all, we need to introduce jquery js package
02 jQuery (document) .ready (function () {
03 $ .ajax ({
04 type
 : "get",
// jquey does not support post domain cross domain
05 async: false,
06 url
 : "http://api.taobao.com/apitools/ajax_props.do",
 // URL for cross-domain request
07 dataType
 : "jsonp",
08 // Pass to the request handler to obtain the parameter name of the jsonp callback function name (default: callback)
09 jsonp:
"jsoncallback",
10 // Customized jsonp callback function name, the default is the random function name automatically generated by jQuery
11 jsonpCallback: "success_jsonpCallback",
12 // After successfully obtaining the json data on the cross-domain server, the callback function will be executed dynamically
13 success
 : function (json) {
14 alert (json);
15}
16});
17});
Sample code on the server side, using java as an example:

The server-side code is the main point. At first, I thought that as long as the client can directly access the domain through jsonp, it is not the case. It needs the support of the server.

01 public void jsonpTest ()
throws IOException {
02 HttpServletRequest
 request = ServletActionContext.getRequest ();
03 HttpServletResponse
 response = ServletActionContext.getResponse ();
04 // According to the parameter name of the jsonp callback function specified by html, get the name of the callback function
05 // The value of callbackName is actually: success_jsonpCallback
06 String
 callbackName = (String) request.getAttribute ("jsoncallback");
07 // Simply simulate a json string, you can actually use Google's gson to convert, the number of times through string stitching
08 // {"name": "张三", "age": 28}
09 // \ is to escape the "number"
10 String
 jsonStr = "{\" name \ ": \" 张三 \ ", \" age \ ": 28}";
11 // The final returned data is: success_jsonpCallback ({"name": "张三", "age": 28})
12 String
 renderStr = callbackName + "(" + jsonStr + ")";
13 response.setContentType ("text / plain; charset = UTF-8");
14 response.getWriter (). Write (renderStr);
15}
The principle of jsonp:

First register a callback on the client (eg: 'jsoncallback'), and then pass the name of the callback (eg: success_jsonpCallback) to the corresponding processing function on the server side.

The server first generates json data that needs to be returned to the client. Then use javascript syntax to generate a function whose name is the value of the parameter (jsoncallback) passed (success_jsonpCallback).

Finally, the json data is directly placed in the function as a parameter, so that a js syntax document is generated and returned to the client.
The client browser parses the script tag and uses the data returned by the server as parameters,
It is passed into the client's predefined callback function (such as the success: function (json) encapsulated by the jquery $ .ajax () method in the above example).

In fact, cross-domain is to dynamically add script to load data, can not directly obtain data, so you need to use a callback function.

 

2. Use jquery getJson to read data across domains

In fact, the basic principle of the getJson method is the same as the way ajax uses jsonp.

GetJson is commonly used in jquery to get 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 is required. Specifies which URL to send the request.
data is optional. Specifies the data sent to the server along with the request.
success (data, status, xhr)
Optional. Specifies the function to run when the request is successful.

Additional parameters:

response-contains the result data from the request
status-contains the status of the request
xhr-contains the XMLHttpRequest object
 

 

This function is a shorthand ajax function, which is actually equivalent to:

 

$ .ajax ({
  url: url,
  data: data,
  success: callback,
  dataType: json
});
 

To be honest, let's look at how to use getJson to obtain data across domains.

 

Sample code for html page:

$ .getJSON ("http://api.taobao.com/apitools/ajax_props.do&jsoncallback=?",
    function (data) {
        alert (data);
    }
);
Implementation principle:

When sending a request, you need to pass a callback function name to the server. The server gets the name of the callback function, and then returns the returned data to the client in the form of parameters, so that the client can be transferred.

Therefore, the jsoncallback =? Parameter must be placed after the address of the request URL. Jquery will automatically replace the? Number with the name of the automatically generated callback function.

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

So I want to compare with the ajax method, that is, one of the callback functions is the automatically generated function name, and the other is the manually specified function name.



Source cited: http://www.duwaiweb.com/blog/20120918_e51195f8-2261-48cf-a883-3013a576fa51.html
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.