关于ie8的问题和前后端分离跨域以及ajax和原生js发送异步请求
由于客户需要做一个答题系统,于是我采用了springboot和vue+iview前后端分离来写,但是客户那面机器比较老,大部分是ie8浏览器,所以做了改造!
1、第一版:springboot+vue+iview(注:前后端分离会遇到跨域请求,于是在后端设置下跨域如下:)
package com.clinroom.core.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableWebMvc
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowCredentials(true).allowedHeaders("*")
.allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS").allowedOrigins("*")
.maxAge(3600);
}
};
}
}
2、但是客户那面电脑比较老大部分是ie8,由于ie8不支持vuejs所以页面改用了原生的html页面,此时请求后台用的是ajax,好不容易解决了这个问题,但是发现ie8不支持ajax请求,由于时间问题也没做处理,改用了原生的js请求。
//创建XMLHttpRequest对象
function createXmlHttp() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("浏览器太老,不能使用ajax");
}
}
}
return xmlHttp;
}
// 1. 创建XMLHttpRequest对象
var xmlHttp = createXmlHttp();
// 2. 调用open方法获取跟服务器的连接
/*
method: 请求方式 get post
url:请求路径
async:表示同步请求还是异步请求 true:异步
*/
xmlHttp.open("GET",
"http://www.baidu.com", true);
// 3. 调用send方法, 向服务器发起请求
// 如果是post请求, 那么需要在send方法中带请求参数
// 如果是get请求, 那么参数为null
xmlHttp.send(null);
// 4. 注册一个监听器
/*
不断地去监听请求的过程返回的一个状态码
在这个时候我们只需要关注readyState == 4的情况,这个时候说明服务器完成了响应
我们还需要关注另外一个状态码 status是服务器响应过来的, 需要status == 200
*/
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState==4&&xmlHttp.status == 200) {
此时说明响应完毕 我们可以通过xml.responseText 来获取服务器的响应内容(文本内容)
console.log(xmlHttp.responseText);
//开始处理你的业务吧
}
};
3、此时大部分ie8都可以使用了,但是如果用的是云桌面或者服务器系统就不行了,因为ie8又一个安全域问题(由于客户不愿意去手动设置,此时我的解决办法是 使用json.js写数据封装来进行调用)
最后附上ajax请求代码:
$.ajax({
type: "POST",
url: "http://www.baidu.com",
data: {},
cache:false,
success: function(data){
alert(3)
}
});