简易ajax

85 阅读2分钟

ajax用途

前后端交互,其实就是一个前后端通讯,是我们在开发中,必不可少的一个技能,我们用到的技能就是ajax

ajax流程

流程为在前端开发中,在某一时候(页面首次打开渲染的时候,或者点击下一页需要更新数据的时候) 此时通过ajax向后端(服务器端发送一个请求,拿到所谓的数据)发送请求需要一些参数(就是高数后端需要什么东西),如果你不知道,那么问你的组长要一个接口文档.

简单的ajax测试

  • 1.创建一个xhr
    const xhr=new XMLHttpRequest()
  • 2.配置ajax对象,xhr.onpen('请求方式','请求地址')
    xhr.open("GET","http://localhost:8888/test/second") ps:自己主机上的json测试
  • 4.接受请求
    这儿可以通过ajax的状态码来判断是否接受 xhr.onreadystatechange=function(){
    if(xhr.readyState===4){
    console.log('当前浏览器已经完全解析完毕返回数据为:'+xhr.responseText
    }
    }
    可替换下文
    xhr.onload=function(){
    console.log(JSON.parse(xhr.responseText));
    }
  • 3.发送请求 xhr.send()

关于POST

post请求传参时需要配置content-type(请求头内的属性)
xhr.setRequestHeader('contentrle-type', 'application/x-www-form-uncoded')
post由很多请求头这只是其中之一

// 请求首行

POST /hello/index.jsp HTTP/1.1

//请求头信息

Host: localhost

User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

Accept-Language: zh-cn,zh;q=0.5

Accept-Encoding: gzip, deflate

Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7

Connection: keep-alive

Referer: http://localhost/hello/index.jsp

Cookie: JSESSIONID=369766FDF6220F7803433C0B2DE36D98

Content-Type: application/x-www-form-urlencoded 

Content-Length: 14 

// 这里是空行

//POST有请求正文

username=hello

发送请求也可以传参 xhr.send('name=张三&age=18')
最后我们封装一个ajax函数

封装ajax简易版

function myAjax(options) {
     //1.验证 参数中的url必传
     console.log(options.url);
     if (options.url === undefined) throw new Error("参数中缺少必填项目") //返回一个错误
     if (!(options.type === undefined || typeof (options.type) === 'string')) throw new Error('参数错误,不符合')
     //1.2剩余参数格式校验
     if (!(options.data === undefined || typeof (options.data) === 'string')) throw new Error("")
     if (!(options.async === Boolean || (options.async) === undefined)) throw new Error("不太行")
     //2.封装默认值
     const _options = {
       url: options.url,
       type: options.type || 'GET',
       date: options.data || '',
       //控制检测符,该符号的特点,只会再左侧的值为空值的时候返回由侧,比如左侧为:null,undefined
       async: options.async ?? true
     }
     const xhr = new XMLHttpRequest()
     xhr.open(_options.type, _options.url, _options.async)
     xhr.onload = function () {
       console.log(xhr.responseText)
     }
     xhr.send()
     console.log(options.async);
   }
   myAjax({
     url: 'http://localhost:8888/test/first',
     // async: 123,
     // data: 'name=zhangsan'
     // type: ''
   })