Implementation of jquery's ajax and getJson cross-origin acquisition of json data _ jquery-js tutorial

Source: Internet
Author: User
This article mainly introduces the implementation of jquery's ajax and getJson cross-origin acquisition of json data. If you need it, refer to it, I hope it will help you. Many developers use jquery to interact with the server on the front end, so it is easy to think that jquery can be used on the front end to read data from any site. Recently, when launching a project, we wanted to share data with a project of a third-party company, because we decided to directly read data in html because we thought that we would not occupy server resources, it does not go through the server. Then we encountered cross-origin access in the browser.

Cross-origin security restrictions refer to the browser, and the server does not have cross-origin security restrictions.

Currently, there are two common cross-origin access methods for browsers:

1. Cross-origin through jQuery ajax, which is actually implemented in jsonp mode.

Jsonp is short for json with padding. It allows the server to generate script tags to return to the client, that is, to dynamically generate javascript tags and read data through javascript callback.

Sample html page code:

The Code is as follows:


// First introduce jquery's js package
JQuery (document). ready (function (){
$. Ajax ({

Type: "get", // jquey does not support cross-origin post.

Async: false,

Url: "http://api.taobao.com/apitools/ajax_props.do", // URL of the Cross-origin request

DataType: "jsonp ",

// The parameter name passed to the request processing program to obtain the jsonp callback function name (default: callback)

Jsonp: "jsoncallback ",

// Custom jsonp callback function name. The default value is the random function name automatically generated by jQuery.

JsonpCallback: "success_jsonpCallback ",

// After the json data on the Cross-origin server is obtained, the callback function is dynamically executed.

Success: function (json ){

Alert (json );
}
});
});


Sample code on the server. java is used as an example:

The server-side code is the focus. I started to think that as long as the client can directly access cross-origin through jsonp, the server-side support is not required.

The Code is as follows:


Public void jsonpTest () throws IOException {

HttpServletRequest request = ServletActionContext. getRequest ();

HttpServletResponse response = ServletActionContext. getResponse ();

// Obtain the name of the callback function based on the parameter name of the jsonp callback function specified in html.

// The value of callbackName is success_jsonpCallback.

String callbackName = (String) request. getAttribute ("jsoncallback ");

// Simulate a json string. You can use google's gson to convert the string.

// {"Name": "zhangsan", "age": 28}

// \ Escape the "Number

String jsonStr = "{\" name \ ": \" Zhang San \ ", \" age \ ": 28 }";

// The final returned data is success_jsonpCallback ({"name": "James", "age": 28 })

String renderStr = callbackName + "(" + jsonStr + ")";

Response. setContentType ("text/plain; charset = UTF-8 ");

Response. getWriter (). write (renderStr );
}


Jsonp principle:

Register a callback (for example, 'jsoncallback') on the client, and pass the callback name (for example, success_jsonpCallback) to the corresponding processing function on the server.

The json data that the server returns to the client. Then, a function is generated in javascript syntax. The function name is the value of the passed parameter jsoncallback (success_jsonpCallback ).

Finally, place the json data directly in the function as an input parameter. In this way, 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 a parameter,
Passed in to the pre-defined callback function of the client (success: function (json) encapsulated by the jquery $. ajax () method in the preceding example.

In fact, cross-origin loads data by dynamically adding scripts, and data cannot be directly obtained. Therefore, a callback function is required.

2. Use getJson of jquery to read data across domains

In fact, the basic principle of getJson is the same as that of ajax using jsonp.

GetJson is commonly used in jquery to obtain remote data and return data in json format. The function prototype is as follows:

JQuery. getJSON (url, data, success (data, status, xhr ))

Parameters Description
Url Required. Specifies the URL of the request.
Data Optional. Specifies the data sent to the server together with the request.
Success (data, status, xhr)

Optional. Specifies the function that runs when the request is successful.

Additional parameters:

  • Response-Contains the result data from the request
  • Status-Contains the Request status.
  • Xhr-Contains the XMLHttpRequest object.

This is an abbreviated ajax function, which is equivalent:

The Code is as follows:


$. Ajax ({
Url: url,
Data: data,
Success: callback,
DataType: json
});


Let's get to the bottom. Next we will look at how to use getJson to retrieve data across domains.

Sample html page code:

The Code is as follows:


$. GetJSON ("http://api.taobao.com/apitools/ajax_props.do&jsoncallback=? ",
Function (data ){
Alert (data );
}
);


Execution principle:

When sending a request, you need to pass a callback function name to the server. The server obtains the callback function name and returns the returned data to the client in the form of parameters, in this way, the client can be tuned.

Therefore, jsoncallback =? For such a parameter, jquery will? Number is automatically replaced with the name of the automatically generated callback function.

Therefore, the actual request is:Http://api.taobao.com/apitools/ajax_props.do&jsoncallback=jsonp1322444422697

Therefore, we want to compare it with the ajax method, that is, the callback function is an automatically generated function name, and the other is a 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.