jQuery cross-domain access problem solution_jquery
Time flies so fast, and when I was pulled back to the js battlefield, the scar of cross-domain problems started to hurt again.
Fortunately, with the help of jquery, cross-domain problems seemed not so difficult. This time too I took this opportunity to get to the bottom of the cross-domain issue, combined with the actual development project, checked the relevant information, and finally solved the cross-domain issue. It is necessary to write down a memo.
The cross-domain security restrictions are Refers to the browser side. There are no cross-domain security restrictions on the server side.
So the "cross-domain access" work is completed through the local server side through a method similar to httpclient, and then AJAX is used on the browser side to obtain this It is also possible to indirectly complete cross-domain access by using the URL corresponding to the "cross-domain access" on the machine server. However, it is obvious that the development volume is relatively large, but the restrictions are minimal. Many widget open platform server sides (such as Sohu Blog Open Platform) are actually It's not within the scope of this discussion.
What we want to discuss is the real cross-domain access on the browser side. What is recommended is that jQuery $.ajax() currently supports cross-domain access in the get method, which actually uses jsonp
Real case:
var qsData = {'searchWord':$("#searchWord").attr("value"),'currentUserId':$("#currentUserId").attr("value"),'conditionBean.pageSize' :$("#pageSize").attr("value")};
$.ajax({
async:false,
url: http://cross-domain dns/document !searchJSONResult.action,
type: "GET",
dataType: 'jsonp',
jsonp: 'jsoncallback',
data: qsData,
timeout: 5000,
beforeSend : function(){
//jsonp This method is not triggered. The reason may be that if dataType is specified as jsonp, it is no longer an ajax event
},
success: function (json) {/ /The callback function predefined by jquery on the client side will be dynamically executed after successfully obtaining the json data on the cross-domain server
if(json.actionErrors.length!=0){
alert(json. actionErrors);
}
genDynamicContent(qsData,type,json);
},
complete: function(XMLHttpRequest, textStatus){
$.unblockUI({ fadeOut: 10 });
},
error: function(xhr){
//This method is not triggered in jsonp mode. The reason may be that if dataType is specified as jsonp, it is no longer an ajax event
//Request Error handling
alert("Request error (please check the relevance network status.)");
}
});
Note: $.getJSON(" http://cross-domain dns/document!searchJSONResult.action?name1=" value1 "&jsoncallback=?",
function(json){
if(json. Attribute name==value){
//Execution code
}
});
This method is actually an advanced encapsulation of the $.ajax({..}) api in the above example. Some of the underlying parameters of $.ajax api are encapsulated and invisible.
In this way, jquery will be assembled into the following url get request
http://cross-domain dns/document!searchJSONResult.action?&jsoncallback =jsonp1236827957501&_=1236828192549&searchWord=use case¤tUserId=5351&conditionBean.pageSize=15
On the response side (http://cross-domain dns/document!searchJSONResult.action),
through jsoncallback = request.getParameter(" jsoncallback") Get the js function name that will be called back later on the jquery side: jsonp1236827957501
Then the content of the response is a Script Tags: "jsonp1236827957501("json array generated according to the request parameters")";
jquery will pass the callback The method dynamically loads and calls this js tag:jsonp1236827957501 (json array);
This achieves the purpose of cross-domain data exchange.
The most basic principle of jsonp is: dynamically add a <script> tag , and the src attribute of the script tag has no cross-domain restrictions. In this way, this cross-domain method has nothing to do with the ajax XmlHttpRequest protocol. <br>In this way, the "jQuery AJAX cross-domain issue" has become a false proposition, and the jquery $.ajax method name is misleading. <br>If set to dataType: 'jsonp', this $.ajax method has nothing to do with ajax XmlHttpRequest, and is replaced by the JSONP protocol. <br>JSONP is an unofficial protocol that allows the integration of Script tags on the server side Return to the client and achieve cross-domain access through javascript callback <br>JSONP is JSON with Padding. Due to the restrictions of the same-origin policy, XmlHttpRequest is only allowed to request resources from the current source (domain name, protocol, port). If we want to make a cross-domain request, <br> we can make a cross-domain request by using the script tag of html and return the script code to be executed in the response, where the javascript object can be passed directly using JSON. <br>This cross-domain communication method is called JSONP. <br><br>jsonCallback function jsonp1236827957501(....): It is registered by the browser client. After obtaining the json data on the cross-domain server, the callback function <br><br>Jsonp principle: <br><br>First register a callback (such as: 'jsoncallback') on the client, and then pass the callback name (such as: jsonp1236827957501) to the server. <br><br>At this time, the server first generates json data. <br><br>Then use javascript syntax to generate a function. The function name is the value jsonp1236827957501 of the passed parameter 'jsoncallback'. <br><br>Finally, place the json data directly as a parameter. function, this generates a js syntax document and returns it to the client. <br><br>The client browser parses the script tag and executes the returned javascript document. At this time, the javascript document data is passed as a parameter. <br>The callback function predefined by the client (such as jquery in the above example) The success: function (json) encapsulated by the $.ajax() method. (Dynamic execution of the callback function) <br><br>It can be said that the jsonp method is in principle the same as <script src="http://cross-domain /...xx.js"></script> are consistent (qq space uses this method to achieve cross-domain data exchange). JSONP is a script injection (Script Injection) behavior, so there are Certain security risks.
Note that jquey does not support cross-domain posting.
Why?
Although using post to dynamically generate an iframe can achieve the purpose of post cross-domain (with some js This is how great people patch jquery 1.2.5), but this is a relatively extreme method and is not recommended.
It can also be said that the cross-domain method of get is legal, and the post method is considered safe from a security perspective. It's illegal. As a last resort, don't go too far.
The demand for cross-domain access on the client side seems to have attracted the attention of w3c. According to the information, the html5 WebSocket standard supports cross-domain data exchange, which should be the case. An optional future solution for cross-domain data exchange.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute
