原始ajax、CORS跨域、jsonp跨域
一、原始的ajax
可直接复制到 tomcat9/webapps/ROOT 目录下运行
1、ajax.jsp
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <title>ajax</title> </head> <body> <!-- file name is ajax.jsp --> <div id="myDiv">装数据的盒子</div> <button type="button" onclick="requestData()">请求数据</button> <script> function requestData() { // 创建 XMLHttpRequest对象 var request = new XMLHttpRequest(); // 接收响应 request.onreadystatechange = function () { if (request.readyState == 4 && request.status == 200) { var result = JSON.parse(this.responseText); showData(result) } } // 定义请求 request.open("GET", "/data", true); // ......本jsp同目录下创建一个名字叫data的文件...... request.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); // 发送请求 request.send(); } // 回调函数 function showData(result) { document.getElementById("myDiv").innerHTML = result; } </script> </body> </html>
2、ajax.jsp同目录下的文件名为”data“的文件的内容
"中华人民共和国"
二、CORS ajax跨域
1、修改上面的ajax.jsp文件里的ajax的访问路径为:
request.open("GET", "http://120.46.219.162:9999/data", true);
2、配置第三方服务器tomcat9的CORS策略
tomcat9/conf/web.xml添加如下内容:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<filter> <filter-name>CorsFilter</filter-name> <filter-class>org.apache.catalina.filters.CorsFilter</filter-class> <init-param> <param-name>cors.allowed.origins</param-name> <param-value>*</param-value> </init-param> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
3、第三方服务器名为”data“的文件的内容
"北海龙王"
三、 JSONP 跨域
1、web 应用A
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <!DOCTYPE html> <html> <head> <title>jsonp</title> </head> <body> <div id="myDiv">装数据的盒子</div> <button type="button" onclick="requestData()">请求数据</button> <script> function addScriptTag(src){ var script = document.createElement('script'); script.setAttribute("type","text/javascript"); script.src = src; document.body.appendChild(script); } function requestData() { addScriptTag("http://120.46.219.162:9999/call.js"); } function callback(data) { document.getElementById("myDiv").innerHTML = data; } </script> </body> </html>
2、web 应用B call.js 文件内容
callback("I am Jack");