JS XML/XHR

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...')
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值