jquery Ajax and Getjson The realization method of obtaining JSON data across domains _jquery

Source: Internet
Author: User
Tags script tag domain server

Many developers use jquery to interact with the front-end and server side of the data, so it's easy to assume that using jquery on the front end can read any site's data. Recently in the development, because to and a third party company's data sharing, because of the consideration of more than the resources of the server, so decided to directly in the HTML data read, do not go to the server side of the relay. And then it just happens to be a problem with browser-side Cross-domain access.

Cross-domain security restrictions are the browser-side, the server side does not exist cross-domain security restrictions.

There are two commonly used methods for browser-side Cross-domain access:

1, through jquery Ajax to cross domain, this is actually adopted 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 return to the client, that is, dynamically generating JavaScript tags, which enable data reading through JavaScript callback.

HTML page End Sample code:

Copy Code code as follows:

The first step is to 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.taobao.com/apitools/ajax_props.do ',//cross-domain URL for request

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, default to jquery automatically generated random function name

Jsonpcallback: "Success_jsonpcallback",

This callback function is executed dynamically after successful capture of JSON data on a cross-domain server

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.

Copy Code code as follows:

public void Jsonptest () throws ioexception{

HttpServletRequest request = Servletactioncontext.getrequest ();

HttpServletResponse response = Servletactioncontext.getresponse ();

Gets the name of the callback function, based on the parameter name of the JSONP callback function specified by HTML

The value of Callbackname is actually: Success_jsonpcallback

String callbackname = (string) request.getattribute ("Jsoncallback");

Simple simulation of a JSON string, can actually use Google's Gson for conversion, the number of times through string concatenation

{' name ': ' John ', ' Age ': 28}

\ is escaping for "number"

String jsonstr = "{\ name\": \ "john \", \ "age\": 28} ";

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

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. Use jquery's 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))

Parameters Description
Url Necessary. Specify which URL to send the request to.
Data Optional. Specify the data to be sent to the server along with the request.
Success (DATA,STATUS,XHR)

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 state of the request
  • xhr -Contains XMLHttpRequest objects

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

Copy Code code 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:

Copy Code code as follows:

$.getjson ("http://api.taobao.com/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.taobao.com/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.

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.