Obtain JSON data through Ajax and getjson in jquery

Source: Internet
Author: User

Many developers use jquery to interact with the server on the front end, so it is easy to think that jquery can be used to read data from any site on the front end. 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:

01 // First introduce jquery's Js package
02 jQuery(document).ready(function(){
03     $.ajax({
04         type : "get", // Jquey does not support cross-origin post.
05         async:false,
06         url : "http://api.taobao.com/apitools/ajax_props.do", // The URL of the Cross-origin request
07         dataType : "jsonp",
08         // The parameter name passed to the request processing program to obtain the jsonp callback function name (default: callback)
09         jsonp: "jsoncallback",
10         // Custom jsonp callback function name. The default value is the random function name automatically generated by jquery.
11         jsonpCallback:"success_jsonpCallback",
12         // After the JSON data on the Cross-origin server is obtained, the callback function is dynamically executed.
13         success : function(json){
14             alert(json);
15         }
16     });
17 });

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.

01 public void jsonpTest() throws IOException{
02     HttpServletRequest request = ServletActionContext.getRequest();
03     HttpServletResponse response = ServletActionContext.getResponse();
04     // Obtain the name of the callback function based on the parameter name of the jsonp callback function specified in HTML.
05     // The value of callbackname is success_jsonpcallback.
06     String callbackName = (String)request.getAttribute("jsoncallback");
07     // Simulate a JSON string. You can use Google's gson to convert the string.
08     // {"Name": "zhangsan", "Age": 28}
09     // \ Escape the "Number
10     String jsonStr = "{\" Name \ ": \" Zhang San \ ", \" Age \ ": 28 }";
11     // The final returned data is success_jsonpcallback ({"name": "James", "Age": 28 })
12     String renderStr = callbackName+"("+jsonStr+")";
13     response.setContentType("text/plain;charset=UTF-8");
14     response.getWriter().write(renderStr);
15 }

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:

 

$.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:

$.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.

So the final 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.

 

This article first in the outside network official blog, reprinted please note the Source: 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.