我的代码
预习:http://javascript.ruanyifeng.com/bom/ajax.html
2005年2月,AJAX 这个词第一次正式提出,它是 Asynchronous JavaScript and XML 的缩写,指的是通过 JavaScript 的异步通信,从服务器获取 XML 文档从中提取数据,再更新当前网页的对应部分,而不用刷新整个网页。后来,AJAX 这个词就成为 JavaScript 脚本发起 HTTP 通信的代名词,也就是说,只要用脚本发起通信,就可以叫做 AJAX 通信。①
具体来说,AJAX 包括以下几个步骤。
1.创建 XMLHttpRequest 实例
2.发出 HTTP 请求
3.接收服务器传回的数据
4.更新网页数据①
概括起来,就是一句话,AJAX 通过原生的XMLHttpRequest对象发出 HTTP 请求,得到服务器返回的数据后,再进行处理。现在,服务器返回的都是 JSON 格式的数据,XML 格式已经过时了,但是 AJAX 这个名字已经成了一个通用名词,字面含义已经消失了。①
XMLHttpRequest对象是 AJAX 的主要接口,用于浏览器与服务器之间的通信。尽管名字里面有XML和Http,它实际上可以使用多种协议(比如file或ftp),发送任何格式的数据(包括字符串和二进制)。①
注意,AJAX 只能向同源网址(协议、域名、端口都相同)发出 HTTP 请求,如果发出跨域请求,就会报错(详见《同源政策》和《CORS 通信》两章)。①
下面是XMLHttpRequest对象简单用法的完整例子。
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
// 通信成功时,状态值为4
if (xhr.readyState === 4){
if (xhr.status === 200){
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.open('GET', '/endpoint', true);
xhr.send(null);
还没看!!!
完整代码:https://github.com/FrankFang/nodejs-test-cors
金句:
- 你才返回对象,你全家都返回对象
- JS 是一门语言,JSON 是另一门语言,JSON 这门语言抄袭了 JS这门语言
- AJAX 就是用 JS 发请求
- 响应的第四部分是字符串,可以用 JSON 语法表示一个对象,也可以用 JSON 语法表示一个数组,还可以用 XML 语法,还可以用 HTML 语法,还可以用 CSS 语法,还可以用 JS 语法,还可以用我自创的语法
讲义
如何发请求?
用 form 可以发请求(post和get都可以),但是会刷新页面或新开页面
用 a 可以发 get 请求,但是也会刷新页面或新开页面
用 img 可以发 get 请求,但是只能以图片的形式展示
用 link 可以发 get 请求,但是只能以 CSS、favicon 的形式展示
用 script 可以发 get 请求,但是只能以脚本的形式运行
![](https://img.haomeiwen.com/i6007177/f4d534906c8f7858.png)
有没有什么方式可以实现
- get、post、put、delete 请求都行
- 想以什么形式展示就以什么形式展示
微软的突破
IE 5 率先在 JS 中引入 ActiveX 对象(API),使得 JS 可以直接发起 HTTP 请求。
随后 Mozilla、 Safari、 Opera 也跟进(抄袭)了,取名XMLHttpRequest,并被纳入 W3C 规范
![](https://img.haomeiwen.com/i6007177/50aa4daad66984c9.png)
AJAX
Jesse James Garrett 将如下技术取名叫做 AJAX:异步的 JavaScript 和 XML
(async javascript and xml)
- 使用 XMLHttpRequest 发请求
- 服务器返回 XML 格式的字符串
- JS 解析 XML,并更新局部页面
如何使用 XMLHttpRequest
myButton.addEventListener('click', (e)=>{
let request = new XMLHttpRequest()
request.open('get', '/xxx') // 配置request
request.send()
request.onreadystatechange = ()=>{
if(request.readyState === 4){
console.log('请求响应都完毕了')
console.log(request.status)
if(request.status >= 200 && request.status < 300){
console.log('说明请求成功')
console.log(typeof request.responseText)
console.log(request.responseText)
let string = request.responseText
// 把符合 JSON 语法的字符串
// 转换成 JS 对应的值
let object = window.JSON.parse(string)
// JSON.parse 是浏览器提供的
console.log(typeof object)
console.log(object)
console.log('object.note')
console.log(object.note)
}else if(request.status >= 400){
console.log('说明请求失败')
}
}
}
})
// 后端代码
}else if(path==='/xxx'){
response.statusCode = 200
response.setHeader('Content-Type', 'text/json;charset=utf-8')
response.setHeader('Access-Control-Allow-Origin', 'http://frank.com:8001')
response.write(`
{
"note":{
"to": "小谷",
"from": "方方",
"heading": "打招呼",
"content": "hi"
}
}
`)
response.end()
google搜索xml mime type
*后端返回xml格式
else if(path === '/xxx'){
response.statusCode = 200
response.setHeader('Content-Type', 'text/xml')
response.write(`
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
`)
response.end()
}
-
readyState
image.png
my_xml.addEventListener('click',function(){
let request = new XMLHttpRequest()
console.log(request.readyState)
request.open('POST','/xxx')
console.log(request.readyState)
request.send()
var myint=setInterval(function(){
console.log(request)
if(request.readyState==4){
clearInterval(myint)
}
},1)
})
![](https://img.haomeiwen.com/i6007177/030230b14aaafa67.png)
my_xml.addEventListener('click',function(){
let request = new XMLHttpRequest()
request.onreadystatechange=function(){
console.log(request.readyState)
if(request.readyState===4){
console.log('请求响应都完毕了')
if(request.status>=200 && request.status<300){
console.log('说明请求成功')
console.log(`响应的数据是${request.responseText}`)
}else{
console.log('说明请求失败')
}
}
}
request.open('POST','/xxx')//配置request
request.send()
})
![](https://img.haomeiwen.com/i6007177/95d682fc6d3895ca.png)
-
得到了xml格式的文本,怎么解析xml呢
js解析xml.png
my_xml.addEventListener('click',function(){
let request = new XMLHttpRequest()
request.onreadystatechange=function(){
console.log(request.readyState)
if(request.readyState===4){
console.log('请求响应都完毕了')
if(request.status>=200 && request.status<300){
console.log('说明请求成功')
console.log(`响应的数据是${request.responseText}`)
//解析xml
let domParser=new DOMParser();
let xmlDoc=domParser.parseFromString(request.responseText,'text/xml' );
let to=xmlDoc.getElementsByTagName('to')[0].textContent
let content=xmlDoc.getElementsByTagName('content')[0].textContent
alert(`to:${to}\r\ncontent:${content}`)
}else{
console.log('说明请求失败')
}
}
}
request.open('POST','/xxx')//配置request
request.send()
})
xml解析起来比较麻烦,那有没有什么简单的方法可以用来表示有结构的数据呢?
JSON —— 一门新语言
http://json.org
json和js的区别?⬇️
![](https://img.haomeiwen.com/i6007177/34029f97d78ce65d.png)
![](https://img.haomeiwen.com/i6007177/eb824f77bc139ac3.png)
![](https://img.haomeiwen.com/i6007177/c6bdee53fb081fb0.png)
同源策略
为什么form表单提交没有跨域问题,但ajax提交有跨域问题?
用form表单给https://www.baidu.com发送get请求,可以成功
用ajax给https://www.baidu.com发送get请求,打开开发者工具,console报下面的错误↓
![](https://img.haomeiwen.com/i6007177/638de8f731789d01.png)
(https://www.zhihu.com/question/31592553)
只有 协议+端口+域名 一模一样才允许发 AJAX 请求
一模一样一模一样一模一样一模一样一模一样一模一样一模一样一模一样
- http://baidu.com 可以向 http://www.baidu.com 发 AJAX 请求吗 no
- http://baidu.com:80 可以向 http://baidu.com:81 发 AJAX 请求吗 no
浏览器必须保证
- 只有 协议+端口+域名 一模一样才允许发 AJAX 请求
- CORS 可以告诉浏览器,我俩一家的,别阻止他
frank.com用ajax请求jack.com,跨域,被阻止了↓
![](https://img.haomeiwen.com/i6007177/65596aabe341d0a8.png)
jack.com在响应的时候,header里面加上Access-Control-Allow-Origin:http://www.frank.com:8001就可以让frank.com请求jack.com了
response.setHeader('Access-Control-Allow-Origin','http://www.frank.com:8001')
response.setHeader('Access-Control-Allow-Origin',*)
后台加一个响应头就可以啦!
Access-Control-Allow-Origin:* 允许所有网站请求
![](https://img.haomeiwen.com/i6007177/270e487a772c20cd.png)
突破同源策略 === 跨域
Cross-Origin Resource Sharing
C O源 R S
跨源资源共享
CORS 跨域
题目
1.请使用原生js来发送ajax请求
let request = new XMLHttpRequest() //step1:new一个XMLHttpRequest对象
request.open('get','/xxx') //step2:配置request
request.send() //step3:发送这个请求
request.onreadystatechange=()=>{ //step4:监听readystate变化
if(request.readyState===4){ //readystate为4表示已经完整收到了响应
if(request.status >= 200 && request.status<300){ //判断status
let string = request.responseText //获取响应的字符串
let object = window.JSON.parse(string) //将json格式的字符串转化为js对象
}
}
}
网友评论