Ajax ( Asynchronous JavaScript and XML )
网页不用重新整理,就能即时地透过浏览器去跟服务器沟通,捞出资料
request - 发出请求
response - 资料回传
request 发出请求时,资料会显示在 request headers,含来源位置 & 网址及浏览器资料等(表明身分)。
response 资料回传後,会回传 response headers 和 response data,response headers 不会显示在网页上,真正回传的资料显示在 response data 里,且 response data 要被编译成什麽格式,由 response headers 里的 Content-type 来决定。
常见 Content-type 格式
- application/x-www-form-urlencoded : (表单格式)
- application/json : (json格式 )
- multipart/form-data : 档案格式(pdf/word/图片/mp4),传送文件使用
- text/plain : 记事本格式(不常用)
- text/html : HTML格式
(这是古老的用法,後面的文章会陆续介绍其他更好用的方法)
用法:
let xhr = new XMLHttpRequest();
console.log(xhr) // 此时会是空物件
// 此时状态 readyState0 - 已经产生了 XMLHttpRequest 但还没连结要捞的资料
readyState
0 - client 端已被建立,但 open() 方法尚未被呼叫。
1 - open() 方法已被呼叫。
2 - send() 方法已被呼叫,发出请求,但还没收到回应。
3 - 已收到部分回应,此时 responseText 会拥有部分资料。
4 - 表示资料已全部接收到,状态为 4 时,就可以把资料显示到网页上了。
xhr.open('方法', '网址', true/false);
xhr.open('get','https://randomuser.me/api/?results=1',true)
// 此时状态 readyState1 - 用了open 但还没把资料传过去
xhr.send(null) // 只是要读取资料 所以传送 null
// 此时状态readyState4 - 代表已经捞到资料,数据完全接收到了,此时 response 里已经有资料
let xhr = new XMLHttpRequest();
xhr.open('get','https://randomuser.me/api/?results=1',true)
xhr.send(null)
因为 open 里面参数是 true 会显示 undefined,抓不到资料,这时候就要利用 onload,等网页跑完再触发事件内容
xhr.onload = function(){
console.log(xhr.response)}
HTTP状态
- 200:资料正确回传
- 404:资料读取错误
- 304:记忆体有快取起来了(清除快取重新载入後就不会看到304)
- 500:服务器错误
使用 RANDOM USER API 实作
let url = "https://randomuser.me/api/?results=1";
let xhr = new XMLHttpRequest();
xhr.open('get',url,true);
xhr.send(null);
xhr.onload = function(){
console.log(JSON.parse(xhr.response));
}
这时候得到的 JSON 资料会长这样
成功取得一笔随机资料,这时候使用 F12 查看会看到 status 显示 200
开了CORS权限,其他开发者才能跨网域捞取资料,若开发者没有开权限,则xhr的status会显示0,没办法取得资料(有时会因为资安问题选择不开)
想知道某笔资料(JSON 或 API)有没有开 CORS,可以上 test-cros.org 查询。
XHR status:200 - 表示资料可取得
XHR status:0 - 表示无开放CORS权限
参考资料:
XMLHttpRequest.readyState
XMLHttpRequest MDN
<<: vok-orm 关联性资料的新增/查询 (上篇) -- d08
>>: day[11] Hello Line - 第一个Line讯息
Chap.I 理论基础 Part 4:统计 & 机率 Analyze the data th...
事情讲不清楚吗? 那我觉得你需要来块白板~(๑•̀ω•́)ノ 给我一块白板,让我们一起得到更多 爲什...
大家好,小弟自己写了一个资料库管理工具,欢迎大家使用并提供建议,谢谢! 软件名称:JasonQuer...
延续昨天的实作,首先我们先来修改一下昨天建置的 Learned Index 类别,还有一些参数需要储...
Conclusion 呼~到今天为止 9 天过去了,Libraries 之间的比较篇章也到今天告一...