search
HomeWeb Front-endJS TutorialHow to solve ajax cross-domain problem

Solution to ajax cross-domain problem: 1. Add Header to the response header to allow access; 2. jsonp only supports get requests but not post requests; 3. httpClient internal forwarding; 4. Use nginx to build an enterprise-level interface gateway Way.

How to solve ajax cross-domain problem

Related free learning recommendations: ajax (Video )

Solution to ajax cross-domain problem:

Solution 1: Add Header to the response header to allow access

Cross-Origin Resource Sharing (CORS) Cross-Origin Resource Sharing

The security foundation of this cross-domain access solution is based on "JavaScript cannot control this HTTP header"

It It is necessary to authorize whether to allow cross-domain access through the HTTP header returned by the target domain.

response.addHeader(‘Access-Control-Allow-Origin:*’);//允许所有来源访问 
response.addHeader(‘Access-Control-Allow-Method:POST,GET’);//允许访问的方式

Solution 2: jsonp only supports get requests but not post requests

Usage: ①Change dataType to jsonp ②jsonp: "jsonpCallback"— ——The actual value sent to the backend is http://a.a.com/a/FromServlet?userName=644064&jsonpCallback=jQueryxxx ③The backend obtains the jsonpCallback in the get request ④Construct the callback structure

$.ajax({
type : "GET",
async : false,
url : "http://a.a.com/a/FromServlet?userName=644064",
dataType : "jsonp",//数据类型为jsonp  
jsonp : "jsonpCallback",//服务端用于接收callback调用的function名的参数
success : function(data) {
alert(data["userName"]);
},
error : function() {
alert('fail');
}
});
 
//后端
        String jsonpCallback = request.getParameter("jsonpCallback");
//构造回调函数格式jsonpCallback(数据)
resp.getWriter().println(jsonpCallback+"("+jsonObject.toJSONString()+")");

JSONP implementation Principle

Under the same-origin policy, pages under a certain server cannot obtain data outside the server, that is, general ajax cannot make cross-domain requests. However, tags such as img, iframe, and script are exceptions. These tags can request data on other servers through the src attribute. Using the open policy of the <script> tag, we can request data across domains. Of course, this requires the cooperation of the server. The core of ajax in Jquery is to obtain non-this page content through XmlHttpRequest, while the core of jsonp is to dynamically add the <script> tag to call the js script provided by the server. </script>

When we normally request a JSON data, the server returns a string of JSON type data, and when we use the JSONP mode to request data, the server returns an executable JavaScript code. . Because the cross-domain principle of jsonp is to dynamically load the src of <script>, we can only pass the parameters through the url, so the type of jsonp can only be get! </script>

Example:

$.ajax({
    url: &#39;http://192.168.10.46/demo/test.jsp&#39;,        //不同的域
    type: &#39;GET&#39;,                                                        // jsonp模式只有GET 是合法的
    data: {
        &#39;action&#39;: &#39;aaron&#39;
    },
    dataType: &#39;jsonp&#39;,                                              // 数据类型
    jsonp: &#39;jsonpCallback&#39;,                                     // 指定回调函数名,与服务器端接收的一致,并回传回来
})

In fact, jquery will be converted internally to

http://192.168.10.46/demo/test.jsp?jsonpCallback=jQuery202003573935762227615_1402643146875&action=aaron

Then dynamic loading

<script type="text/javascript"src="http://192.168.10.46/demo/test.jsp?jsonpCallback= jQuery202003573935762227615_1402643146875&action=aaron"></script>

Then the backend will execute jsonpCallback (pass parameters) and send the data in the form of actual parameters.

The entire process of using JSONP mode to request data: the client sends a request and specifies an executable function name (here jQuery does the encapsulation process and automatically generates a callback function for you and takes out the data For the success attribute method to call, instead of passing a callback handle), the server accepts the jsonpCallback function name, and then sends the data out in the form of actual parameters

(in jquery In the source code, jsonp is implemented by dynamically adding the <script> tag to call the js script provided by the server. jquery will load a global function in the window object. When the <script> code is inserted, the function will be executed. After execution, <script> will be removed. At the same time, jquery has also optimized non-cross-domain requests. If the request is under the same domain name, it will work like a normal Ajax request.) </script>

Solution 3: httpClient internal forwarding

The implementation principle is very simple. If you want to access site A through Ajax in site B to obtain results, there will of course be an ajax cross-domain problem. , but there is no cross-domain problem when accessing site B to obtain results in site B. This method is actually to access the HttpClient of site B through ajax in site B, and then forward the request through HttpClient to obtain the data results of site A. However, this method generates two requests, which is inefficient. However, internal requests cannot be analyzed by packet capture tools and are safe.

$.ajax({
type : "GET",
async : false,
url : "http://b.b.com:8080/B/FromAjaxservlet?userName=644064",
dataType : "json",
success : function(data) {
alert(data["userName"]);
},
error : function() {
alert(&#39;fail&#39;);
}
});
 
@WebServlet("/FromAjaxservlet")
public class FromAjaxservlet extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
//创建默认连接
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建HttpGet对象,处理get请求,转发到A站点
HttpGet httpGet = new HttpGet("http://a.a.com:8080/A/FromServlet?userName="+req.getParameter("userName")); 
                        //执行
CloseableHttpResponse response = httpClient.execute(httpGet);
int code = response.getStatusLine().getStatusCode();
//获取状态
System.out.println("http请求结果为:"+code);
if(code == 200){
                                //获取A站点返回的结果
String result = EntityUtils.toString(response.getEntity());
System.out.println(result);
                                //把结果返回给B站点
resp.getWriter().print(result);
}
response.close();
httpClient.close();
} catch (Exception e) {
}
}
}

Solution 4: Use nginx to build an enterprise-level interface gateway method

www.a.a.com cannot directly request the content of www.b.b.com , you can use nginx to distinguish them based on the same domain name but different project names. What does that mean? That may be a bit abstract. Assume that our company domain name is www.nginxtest.com

When we need to access www.a.a.com through www.nginxtest.com/A, and forward it to www.a.a.com

through nginx We need to access www.b.b.com through www.nginxtest.com/B, and forward it to www.a.a.com through nginx

When we access the company's domain name, it is "same source", but the project name is different , the role of the project name at this time is just to distinguish and facilitate forwarding. If you still don’t understand, first take a look at how I configured it:

server {
        listen       80;
        server_name  www.nginxtest.com;
        location /A {
    proxy_pass  http://a.a.com:81;
index  index.html index.htm;
        }
location /B {
    proxy_pass  http://b.b.com:81;
index  index.html index.htm;
        }
    }

我们访问以www.nginxtest.com开头且端口为80的网址,nginx将会进行拦截匹配,若项目名为A,则分发到a.a.com:81。实际上就是通过"同源"的域名,不同的项目名进行区分,通过nginx拦截匹配,转发到对应的网址。整个过程,两次请求,第一次请求nginx服务器,第二次nginx服务器通过拦截匹配分发到对应的网址。

相关免费学习推荐:javascript(视频)

The above is the detailed content of How to solve ajax cross-domain problem. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment