ajax学习笔记

Ajax:浏览器和服务器之间数据交互的方式,底层是基于浏览器提供的xhr对象

 

基于xhr发起get请求

  1. 创建实例
  2. Open函数
  3. Send函数
  4. Onreadystatechange事件

const xhr=new XMLHttpRequest()

        xhr.open("GET","http://www.liulongbin.top:3006/api/getbooks")

        xhr.send()

        xhr.onreadystatechange=function(){

            if(xhr.readyState == 4 && xhr.status == 200){

                console.log(xhr.responseText)

            }

        }

Json:字符串,存储数据。两种结构:数组和对象

Jsonjs对象  JSON.parse()

js对象转json字符串 JSON.stringfy()

 

Axios:对ajax进行封装

基于axios发起请求

  1. 导入axios第三方库   params={id:1}
  2. axios.get(url,{params:params}).then(function(res){  res.data })
  3. axios.post(url,params).then(function(res){ })

 

直接使用axios进行请求

axios{

method:“GET”,

url:””,

Params:{ }

}.then( function(res){

Console.log(res.data)

})

 

axios{

method:“POST”,

url:””,

data:{ }

}.then( function(res){

Console.log(res.data)

})

 

posted @ 2023-03-30 15:58  无趣鲸鱼  阅读(27)  评论(0)    收藏  举报