理解 ajax 的跨域访问
 

2Ajax 跨域介绍

 
跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器
对 JavaScript 施加的安全限制。
 
什么是同源策略: 所谓的同源,指的是域名、协议、端口均相等。
不同源的系统使用 ajax 发送求,会存在跨域的问题:例如
http://www.abc.com/ 访问 http://www.xyz.com 域名不一致,存在跨域
http://www.abc.com/ 访问 https://www.abc.com 协议不一致,存在跨域
http://www.abc.com:80/ 访问 http://www.abc.com:81 端口不一致,存在跨域 
 
 

3Ajax 跨域问题

 

3.1 建立 ajax-origin 项目

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.bjsxt.ajax.origin</groupId> <artifactId>ajax-origin</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties>
<!-- spring 依赖 --> <spring.version>4.3.18.RELEASE</spring.version> <jstl.version>1.2</jstl.version> <servlet-api.version>2.5</servlet-api.version> <jsp-api.version>2.0</jsp-api.version> <jackson.version>2.9.0</jackson.version>
</properties> <dependencies>
<!-- jsp 相关依赖 -->
<!-- servlet 依赖 -->
<!-- jstl 依赖 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version>
</dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>${servlet-api.version}</version> <scope>provided</scope>
</dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jsp-api</artifactId> <version>${jsp-api.version}</version> <scope>provided</scope>
</dependency>
</dependencies> <build> <finalName>ajax</finalName> <plugins>
<!-- 配置 Tomcat 插件 --> <plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <path>/ajax</path> <port>9090</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
View Code

 

3.2 发送 Ajax 请求

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
function sendAjax(){
$.post("http://localhost:7070/order/loadOrderList02","uid=1234",function(data){
alert(data);
});
}
</script>
</head> <body><a href="javascript:sendAjax()">sendAjax</a>
</body>
</html>
View Code

相关文章:

  • 2021-11-23
  • 2021-06-16
  • 2021-11-10
  • 2022-12-23
  • 2022-12-23
  • 1970-01-01
  • 2021-11-22
猜你喜欢
  • 2021-05-21
  • 2022-12-23
  • 2021-11-22
  • 2021-11-14
相关资源
相似解决方案