Ajax与CORS通信
|
处理跨域的主要方法
本文主要讨论CORS解决AJAX因为浏览器同源策略不能跨域请求数据的问题。 1.JSONPJSONP跨域可以参考下面这篇博客 2.CORS关于CORS细节可以阅读跨域资源共享 CORS 详解。 跨域资源共享 CORS 1. 跨域资源共享CORS(Cross-origin resource sharing) CORS是一个W3C标准,全称是"跨域资源共享"(Cross-origin resource sharing)。它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而解决了AJAX不能跨域请求的问题。 2. CORS需要浏览器和服务器同时支持。 整个CORS通信过程,都是浏览器自动完成,不需要用户参与。对于开发者来说,CORS通信与同源的AJAX通信没有差别,代码完全一样。浏览器一旦发现AJAX请求跨源,就会自动添加一些附加的头信息,有时还会多出一次附加的请求,但用户不会有感觉。 因此,实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信。 CORS允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。 Ajax简介Ajax即“Asynchronous JavaScript and XML”(异步的JavaScript与XML技术) Ajax 是一种用于创建快速动态网页的技术。通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。 XMLHttpRequest对象是浏览器提供的一个API,用来顺畅地向服务器发送请求并解析服务器响应,当然整个过程中,浏览器页面不会被刷新。 创建Ajax步骤:1.创建XMLHttpRequest对象 function createRequest (){
try {
xhr = new XMLHttpRequest();
}catch (tryMS){
try {
xhr = new ActiveXObject("Msxm12.XMLHTTP");
} catch (otherMS) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch (failed) {
xhr = null;
}
}
}
return xhr;
}
2.准备请求
3.发送请求 4.处理响应 xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log(xhr.responseText);
}
}
代码实现如下: HTML <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="myButton">点我</button>
<script src="./main.js"></script>
</body>
</html>
JS myButton=document.getElementById('myButton')
myButton.addEventListener('click',(e)=>{
let xhr=new XMLHttpRequest()
xhr.onreadystatechange=()=>{
if( xhr.readyState===4){
console.log("请求响应都完毕了")
if( xhr.status>=200&& xhr.status<300){
console.log("请求成功")
console.log(typeof xhr.responseText)//判断返回数据的类型是String
console.log( xhr.responseText)
let string= xhr.responseText
let object=window.JSON.parse(string)
console.log(typeof object)
console.log(object)
}else if( xhr.status>=400){
console.log("请求失败")
}
}
}
xhr.open('GET','/xxx')
xhr.send()
})
if(path==='/xxx'){
response.statusCode=200
response.setHeader('Content-Type','text/json;charset=utf-8')
response.write(`
{
"note":{
"to":"xxx","from":"yyy","content":"hello"
}
}
`)
response.end()
}
当发送请求的时候,就会根据
CORS跨域 HTML <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="myButton">点我</button>
<script src="./main.js"></script>
</body>
</html>
JS myButton.addEventListener('click',(e)=>{
let xhr=new XMLHttpRequest()
xhr.open('GET','http://jack.com:8002/xxx')
xhr.onreadystatechange=()=>{
if(xhr.readyState===4){
console.log("请求响应都完毕了")
if(xhr.status>=200&&xhr.status<300){
console.log("请求成功")
console.log(typeof xhr.responseText)
console.log(xhr.responseText)
let string=xhr.responseText
let object=window.JSON.parse(string)
console.log(typeof object)
console.log(object)
}else if(xhr.status>=400){
console.log("请求失败")
}
}
}
xhr.send()
})
if(path==='/xxx'){
response.statusCode=200
response.setHeader('Content-Type','text/json;charset=utf-8')
response.setHeader('Access-Control-Allow-Origin','http://blog1.com:8001')
response.write(`
{
"note":{
"to":"xxx","content":"hello"
}
}
`)
response.end()
}
可以看到当代码没有下面这一行代码时AJAX并不能跨域请求
从结果可以看出,因为浏览器的同源策略,Ajax不能跨域请求 解决的办法是添加
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
