ajax的调用

50 阅读2分钟

ajax的基本创建

//创建ajax对象
let xhr = new XMLHttpRequery();
//请求方式
xhr.open(type,网址)
//发送请求
xhr.send()
//上面请求操作完成之后执行
xhr.onload = function(){
    //response 请求之后服务器反馈的结果
    console.log(xhr.response)
}

ajax的请求方式

get请求

//get第一种请求方式
let xhr = new XMLHttpRequest()
//     test/first  服务器返回是以字符串形式
xhr.open('get','http://localhost:8888/test/first')
xhr.send();
xhr.onload = function(){
    //接受服务器返回的结果    是字符串形式//
    console.log(xhr.response)//哇塞, 你已经成功使用 ajax 发送给我了一个请求, 这是我给你的回应, 我是一个字符串类型 ^_^ !
}


//get 第二种请求方式
let xhr = new XMLHttpRequest()
//   test/second  服务器返回是以json字符串形式
xhr.open('get','http://localhost:8888/test/second')
xhr.send()
xhr.onload = function(){
    console.log(xhr.response)//{"message":"我已经接受到了你的请求, 这是我给你的回应, 我是一个 json 格式","tips":"后端返回给前端的数据","code":1,"age":18}
    //可以根据需求将其转化为对象进行操作
    let res  = JSON.parse(xhr.response)
    //也可以将其解构赋值,取出需要的值
    let {message,code} = JSON.parse(xhr.response)
    console.log(message)//我已经接受到了你的请求, 这是我给你的回应, 我是一个 json 格式
}
    
//get  第三种请求方式
let xhr = new XMLHttpRequest();
//    test/third  返回json字符串形式.可以传递参数
//参数直接写在url网址后面
xhr.open('get','http://localhost:8888/test/third?name=zs&age=15');
xhr.send();
xhr.onload = function(){
      console.log(xhr.response)//{"message":"我接收到了你的请求, 你的请求方式是 GET, 并且正确携带了 'name' 和 'age' 参数给我 ! <(* ̄▽ ̄*)/","code":1,"info":{"msg":"这是你带来的参数, 我还返回给你, 让你看看, 证明你带过来了","name":"zs","age":"15"}}
}

post请求

let xhr = new XMLHttpRequest();
//    test/fourth   post请求,返回也是json字符串
xhr.open('post','http://localhost:8888/test/fourth');
//post  请求需要写一个格式编码   将编码格式转换为form表单的编码格式
xhr.setRequestHeader('content-type','application/x-www-form-urlencoded')
//需要声明一个变量填写参数,然后将参数填写在给send()
let res = 'name=zs&age=25';
xhr.send(res);
xhr.onload = function(){
   console.log(xhr.response) 
}