1. What is cross-domain?
Because the browser adopts the same-origin policy restrictions for security reasons, jQuery cannot directly operate objects or data across domain names. For example: a.com
The a.html page cannot operate the objects or data of the b.html page under the b.com domain name using jQuery, and by default, the test.a.com domain name cannot be operated.
The object or data of test.html. As long as jQuery meets the following conditions, it will be considered a cross-domain name:
1. The main domain is the same, the subdomain is different, such as xxx.aaa.com and yyy.aaa.com
2. The domain name is the same, but the ports are different, such as xxx.aaa.com:8000 and xxx.aaa.com
3. The domain name is the same, but the protocol is different, such as http://www.aaa.com/ and https://www.aaa.com/
Only if the protocol, domain name, and port are exactly the same jQuery will be considered to be not a cross-domain name.
2. Solution to jQuery cross-domain name operation object
1. The situation of the first arrival of the top-level domain name
By default, the a.html page under the a.com domain name cannot operate the test.html object or data under the test.a.com domain name using jQuery. But for this same situation as the top-level domain names, just reset document.domain=a.com in a.html and test.html.
2. The situation where the top-level domain names are different
There are two methods for the a.html page under the a.com domain name, $.getJSON and $.ajax
(1) Cross-domain through jQuery's ajax, which is actually implemented using jsonp method.
jsonp is the abbreviation of json with padding in English. It allows the generation of script tags on the server side to return to the client, that is, dynamically generates javascript tags.
Data reading is realized through the form of javascript callback.
Sample code for html page side:
The code is as follows:
//First of all, you need to introduce jquery's jQuery(document).ready(function(){ $.ajax({ type : "get", //jquey does not support the post method cross-domain async:false, url: "http://api.VeVB.COM/apitools/ajax_props.do", //The URL of cross-domain request dataType: "jsonp", //Pasted to the request handler to obtain the parameter name of the jsonp callback function name (default: callback) jsonp: "jsoncallback", //The custom jsonp callback function name is the default random function name jsonpCallback automatically generated by jQuery:"success_jsonpCallback", //After successfully obtaining json data on the cross-domain server, the callback function will be executed dynamically. Success: function(json){ alert(json); } }); });Server-side sample code, take java as an example:
Server-side code is the key point. I initially thought that as long as the client can directly access across domains through jsonp, it is not the case, and the server-side support is required.
The code is as follows:
public void jsonpTest() throws IOException{ HttpServletRequest request = ServletActionContext.getRequest(); HttpServletResponse response = ServletActionContext.getResponse(); //Get 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"); //Simplely simulate a json string. In fact, you can use Google's gson to convert it. The number of times is spliced 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); }The principle of jsonp:
First register a callback (such as 'jsoncallback') on the client, and then pass the callback name (such as : success_jsonpCallback) to the corresponding processing function on the server side.
The server generates json data that needs to be returned to the client. Then, in the form of javascript syntax, a function is generated, and 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 document of js syntax and returning it to the client.
The client browser parses the script tag and uses the data returned by the server as a parameter.
It is passed into the callback function predefined by the client (as in the above example, the success: function (json) encapsulated by the jquery $.ajax() method).
In fact, cross-domain loads data by dynamically adding scripts, and data cannot be obtained directly, so callback functions are needed.
(2) Use jquery's getJson to read data across domains
In fact, the fundamental principle of getJson method is the same as the way ajax uses jsonp.
GetJson is commonly used in jquery to call to get remote data and return it through json format. The prototype of the function is as follows:
jQuery.getJSON(url,data,success(data,status,xhr))
Parameter description
url required. Specifies which URL to send to the request.
data is optional. Specifies the data sent to the server together with the request.
success(data, status,xhr) is optional. Specifies the function to run when the request is successful.
Additional parameters:
Response - Contains result data from the request
status - contains the status of the request
xhr - Contains XMLHttpRequest object
This function is abbreviated ajax function, which is actually equivalent to:
The code is as follows:
$.ajax({ url: url, data: data, success: callback, dataType: json});Let's get back to the point, let's take a look at how to use getJson to obtain data across domains.
Sample code for html page:
The code is as follows:
$.getJSON("http://api.VeVB.COM/apitools/ajax_props.do&jsoncallback=?", function (data) { alert(data); });Execution principle:
When sending a request, you need to pass a callback callback function name to the server side. The server side 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.
Therefore, after the address of the request URL, you must use the parameter such as jsoncallback=?, and jquery will automatically replace the ? number with the name of the automatically generated callback function.
So the final actual request is: http://api.VeVB.COM/apitools/ajax_props.do&jsoncallback=jsonp1322444422697
So if you want to compare it with the ajax method, that is, the callback function is one of the automatically generated function names and the other is the manually specified function names.
Pay attention to the following points:
1. The address sent to the data recipient must be added with the parameter such as callback=?, and this? is the name of the callback method that will be automatically replaced by Jquery. (In Jquery 1.4, you can specify the name of the callback method yourself)
2. Note that the data sent by the js script cannot be written as var data="{'username':'sanjer','userid':'110'}"; but should be written as var data={username:'sanjer',userid:'110'}, and you should pay attention to this point. To receive data returned by the server, the server must encapsulate the data into a JSON format string and return it together with the callback value. (Please read the above sample code carefully).
3. When calling Jquery's $.getJSON method, Jquery has its own processing, which is actually requested through script's scr, but you should know that the data is finally sent out through the url through get. This determines that the amount of data sent cannot be too much, otherwise the URL will fail to receive it too long (it is impossible to submit it in a post method when the getJSON method is submitted).
If you want to send large data across domains, you can choose the ajax method provided by jQuery, and it is best not to use the getJSON method.
4. The above examples are based on the premise that both aspects of development are under your control. Also, be careful that the security factor of the server program is not high (it is recommended that you do not place important and sensitive logic processing units on the data receiving end).
The above method of java combined with jQuery to achieve cross-domain name acquisition data is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.