ajax的学习记录

XHR理解

使用XMLHttpRequest (XHR)对象可以与服务器交互, 也就是发送ajax请求。前端可以获取到数据,而无需让整个的页面刷新。这使得Web页面可以只更新页面的局部,而不影响用户的操作。

  • xhr对象本身有5种状态:xhr “诞生” 的那一刻就是0状态:

    0:xhr对象在实例化出来的那一刻,就已经是0状态,代表着xhr是初始化状态。

    1:send方法还没有被调用,即:请求没有发出去,此时依然可以修改请求头。

    2:send方法被调用了,即:请求已经发出去了,此时已经不可以再修改请求头。

    3:已经回来一部分数据了,如果是比较小的数据,会在此阶段一次性接收完毕,较大数据,有待于进一步接收。

    4:数据完美的回来了。

原生的ajax请求

  • get请求
   
   1.实例化一个XMLHttpRequest对象
    let xhr = new XMLHttpRequest()

   2.绑定一个名为onreadystatechange事件监听
    xhr.onreadystatechange = function () { 
       if(xhr.readyState === 4 && xhr.status === 200){
        //如果进入此判断,意味着:请求成功了,且数据已经回来了
        console.log(xhr.response)
       }
    }

    3.调用open方法---------用什么方法发?给谁发?带着什么过去?
    xhr.open('get','http://localhost:3000/ajax_get?name=kobe&age=18&t='+Date.now())

    4.调用send方法---------发送请求
    xhr.send()
    
  
  • post请求

    1.实例化一个XMLHttpRequest对象
    let xhr = new XMLHttpRequest()

    2.绑定一个名为onreadystatechange事件监听
    xhr.onreadystatechange = function () {
      if(xhr.readyState === 4 && xhr.status === 200){
        console.log(xhr.response)
        let demo = document.getElementById('demo')
        demo.innerHTML = xhr.response
      }
    }

    3.调用open方法---------用什么方法发?给谁发?带着什么过去?
    xhr.open('post','http://localhost:3000/ajax_post')
    
    特别注意:此处是设置post请求所特有的请求头,若不设置,服务器无法获取参数
    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')

    4.调用send方法---------发送请求
    xhr.send('name=kobe&age=18')


JQuery封装的ajax请求

  • get请求
  
   1、完整的写法
   $.ajax({
      url:'http://localhost:3000/ajax_get',
      method:'get', //发送请求的方式
      data:{name:'kobe',age:41}, //发送请求携带的数据
      //成功的回调
      success:function (result) { 
        console.log(result)
      },
      //失败的回调
      error:function (err) {
        console.log(err)
      }
    })

   2、简单的写法
    $.get('http://localhost:3000/ajax_get',{name:'kobe',age:41},(data)=>{
      console.log(data)
    })


  
 
 
  • post请求
  
   1、完整的写法
    $.ajax({
     url:'http://localhost:3000/ajax_post',
     method:'post', //发送请求的方式
     data:{name:'kobe',age:41}, //发送请求携带的数据
     //成功的回调
     success:function (result) {
       console.log(result)
     },
     //失败的回调
     error:function (err) {
       console.log(err)
     }
   })

   2、简单的写法
    $.post('http://localhost:3000/ajax_post',{name:'kobe',age:41},(data)=>{
      console.log(data)
    })
    
    

猜你喜欢

转载自blog.csdn.net/qq_40844662/article/details/109100862