innerWang / blogs

1 stars 0 forks source link

手写ajax的实现 #4

Open innerWang opened 5 years ago

innerWang commented 5 years ago
GET 方式
var xhr = new XMLHttpRequest()
xhr.open('GET','/xxx' ,true)    //true 表示异步,为默认值
xhr.onload = function(e){
  if(xhr.status >= 200 && xhr.status <300 || xhr.status == 304){
    console.log('获取数据成功')
    console.log(xhr.responseText)
  }else{
    console.log('获取数据失败')
  }
}

xhr.onerror = function(e){
  console.log('连接失败')
}

xhr.send()
POST 方式
var xhr = new XMLHttpRequest()
xhr.open('POST','/xxx',true)
xhr.onload = function(e){
  if(xhr.status >= 200 && xhr.status <300 || xhr.status == 304){
    console.log('获取数据成功')
    console.log(xhr.responseText)
  }else{
    console.log('获取数据失败')
  }
}

xhr.onerror = function(e){
  console.log('连接失败')
}

xhr.send('a=1&b=2')