Home > Web Front-end > JS Tutorial > body text

Implementation method of jquery's ajax and getJson to obtain json data across domains_jquery

WBOY
Release: 2016-05-16 17:01:34
Original
1045 people have browsed it

Many developers are using jquery to interact with data on the front-end and server-side, so it is easy to think that using jquery on the front-end can read the data of any site. When I was developing recently, because I had to share data with a project of a third-party company, and because I was considering not occupying much server resources, I decided to read the data directly in HTML instead of transferring it through the server. Then I just encountered the problem of cross-domain access on the browser side.

Cross-domain security restrictions refer to the browser side, and there are no cross-domain security restrictions on the server side.

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

1. Cross-domain through jQuery’s ajax. This is actually implemented using jsonp.

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

HTML page side sample code:

Copy code The code is as follows:

//First To introduce the js package of jquery
jQuery(document).ready(function(){
$.ajax({

type: "get", //jquey does not support post cross-domain

async:false,

url: "http://api.taobao.com/apitools/ajax_props.do", //Cross-domain request URL

dataType: "jsonp",

//Parameter name passed to the request handler to obtain the jsonp callback function name (default: callback)

jsonp: "jsoncallback",

//Customized jsonp callback function name, the default is a random function name automatically generated by jQuery

jsonpCallback:"success_jsonpCallback",

//After successfully obtaining the json data on the cross-domain server, this callback function will be dynamically executed

success : function(json){

                        alert(json);
Server-side code is the key point. I initially thought that as long as the client can directly access cross-domain access through jsonp, this is not the case and requires server-side support.



Copy code


The code is as follows:

//Get the name of the callback function based on the parameter name of the jsonp callback function specified in HTML
//The value of callbackName is actually: success_jsonpCallback

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

//Simple simulation of a json string, you can actually use Google's gson for conversion, and the number of times is through string splicing

//{"name":"Zhang San","age":28}

//It is to escape the " sign

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

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

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

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

response.getWriter().write(renderStr);

}


Principle of jsonp:

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

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

Finally, the json data is placed directly into the function as a parameter, thus generating a js syntax document and returning it to the client.
The client browser parses the script tag and uses the data returned by the server as a parameter.
passes in the callback function predefined by the client (as encapsulated by the jquery $.ajax() method in the above example success: function (json)).

In fact, cross-domain loading of data is done by dynamically adding scripts. Data cannot be obtained directly, so callback functions need to be used.

2. Use jquery’s 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 obtain 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 Required. Specifies the URL to which the request will be sent.
data Optional. Specifies the data to be sent to the server with the request.
success(data,status,xhr)
参数 描述
url 必需。规定将请求发送的哪个 URL。
data 可选。规定连同请求发送到服务器的数据。
success(data,status,xhr)

可选。规定当请求成功时运行的函数。

额外的参数:

  • response - 包含来自请求的结果数据
  • status - 包含请求的状态
  • xhr - 包含 XMLHttpRequest 对象
Optional. Specifies a function to run when the request succeeds.

Extra parameters:

  • response - Contains result data from the request
  • status - Contains the status of the request
  • xhr - Contains XMLHttpRequest object
This function is the abbreviated ajax function, which is actually equivalent to: Copy code

The code is as follows:


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


Back to business, let’s look at how to use getJson to obtain data across domains.

HTML page sample code: Copy 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 gets the callback function name, and then returns the return data to the client in the form of parameters, so that the client can call it.

So the address that sends the request URL must be followed by a parameter like jsoncallback=?. 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 it with the ajax method, that is, one of the callback functions is an automatically generated function name, and the other is a manually specified function name.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template