说明
通过 xhr.open('GET', 'http://127.0.0.1:8000/ie?t='+Date.now());
一句设置请求中的参数,从而可以防止 IE 浏览器调用缓存
前端文件
<html>
<head>
<meta http-equiv="Access-Control-Allow-Origin" content="*" />
</head>
<body>
<button>press</button>
<div id="content" style="width: 300px;height:200px;border:1px solid;"></div>
</body>
<script>
const btn = document.getElementsByTagName('button')[0];
const content = document.getElementById('content');
btn.onclick = function(){
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:8000/ie?t='+Date.now());
xhr.send('a=200&b=300');//请求体在这里,可以很灵活
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
console.log(xhr.status);
console.log(xhr.statusText);
console.log(xhr.getAllResponseHeaders());
console.log(xhr.response);
content.innerHTML = xhr.response;
}
}
}
}
</script>
</html>
后端文件
const express = require('express');
const app = express()
app.get('/server', (Request, Response)=>{
Response.setHeader('Access-Control-Allow-Origin', '*')
Response.send('Hello Ajax')
})
app.get('/ie', (Request, Response)=>{
Response.setHeader('Access-Control-Allow-Origin', '*')
Response.send('Hello IE')
})
app.post('/server', (Request, Response)=>{
Response.setHeader('Access-Control-Allow-Origin', '*')
Response.send('Hello Ajax-4')
})
app.listen(8000, ()=>{
console.log('8000 running meproject express')
})