XML/JSON
无需刷新页面,一切数据在browser后部执行;
WORKing with txt
设定button的事件
document.getElementById('button').addEventListener('click',loadData); //()在里面则读取时就会调用
//readyState Values
//0:request not initialized
//1:server connection established
//2:request received
//3:processing request
//4:request finished and response is ready
//HTTP statuses
//200 : ok
// 403 forbidden
//404 not found
设定loadData()
onload:
readystatus直接到4;
function loadData(){
//Create an XHR Object
const xhr = new XMLHttpRequest();
//OPEN
xhr.open('GET','data.txt',true); //aschro
//console.log(`READYSTATE`,xhr.readyState);
//1:server connection established
xhr.onload = function(){
console.log(`READYSTATE`,xhr.readyState);
if(this.status === 200){ //成功连接
console.log(this.responseText);
}
}
xhr.send(); //调用上述的xhr
}
onreadystatechange:
从2~4;
需要确认当前readystate是否已经到4;
xhr.onreadystatechange =function(){
//console.log(`READYSTATE`,xhr.readyState);
//2:request received
//3:processing request
//4:request finished and response is ready
//会经历了2,3,4,所以要确认是否已经到4了
if(this.status===200 && this.readyState===4){
console.log(this.responseText);
}
}
onprogress
//Optional -User for spinners/loaders
xhr.onprogress = function(){
console.log(`READYSTATE`,xhr.readyState);
//3:processing request
}
访问失败操作
xhr.onerror =function(){
console.log('Request error...')
}