对Ajax的简单理解与使用

ajax

1.ajax是前后端交互的一种方式

async javascript and xml

通过js向服务器发送请求
服务端返回的响应直接返回给js,不会在页面上显示
这说明js与服务器交互
依赖于浏览器发送请求

//1.实例化 一个可以发送ajax请求的对象
const xhr = new XMLRequestHttp();
//2.配置请求信息.open( 请求方式, url  ,  是否异步)
xhr.open( 'GET', 'url', true )
//3.绑定事件
xhr.onload = function(){
	console.log(xhr.responseText)
}
//4发送请求
xhr.send();

ajax发送带参数的GET请求

const xhr = new XMLHttpRequest();
//直接在地址栏后面拼接queryString的方式携带参数
xhr.open('GET','ulr?a=100&b=200');
xhr.onload = function(){
    console.log(xhr.responseText);
}
xhr.send();

ajax发送带参数的POST请求

const xhr = new XMLHttpRequest();
xhr.open('POST','utl');
xhr.onload = function(){
    console.log(xhr.responseText);
}
//POST请求需要在发送请求之前设置请求头
xhr.setRequestHeader = ('content-type', 'appliaction/x-www-form-urlencoded')
//POST请求的参数直接写在xhr.send()中;
xhr.send('a=100&b=200');
ajax的封装

function ajax(options = {}) {
  if (!options.url) {
    throw new Error('url 必填')
  }
  if (!(options.type == undefined || options.type.toUpperCase() === 'GET' || options.type.toUpperCase() === 'POST')) {
    throw new Error('只接收 GET 或者 POST 请求方式')
  }
  if (!(options.async == undefined || typeof options.async === 'boolean')) {
    throw new Error('async 需要一个 Boolean 数据类型')
  }
  if (!(options.dataType == undefined || options.dataType === 'string' || options.dataType === 'json')) {
    throw new Error('只支持 string 和 json 格式解析')
  }
  if (!(options.data == undefined || typeof options.data === 'string' || Object.prototype.toString.call(options.data) === '[object Object]')) {
    throw new Error('data 参数只支持 string 和 object 数据类型')
  }
  if (!(options.success == undefined || typeof options.success === 'function')) {
    throw new Error('success 传递一个函数类型')
  }
  if (!(options.error == undefined || typeof options.error === 'function')) {
    throw new Error('error 传递一个函数类型')
  }

  // 2. 设置一套默认值
  var _default = {
    url: options.url,
    type: options.type || 'GET',
    async: typeof options.async === 'boolean' ? options.async : true,
    dataType: options.dataType || 'string',
    data: options.data || '',
    success: options.success || function () {},
    error: options.error || function () {}
  }
  if (typeof _default.data === 'object') {
    var str = ''
    for (var key in _default.data) {
      str += key + '=' + _default.data[key] + '&'
    }
    _default.data = str.slice(0, -1)
  }

  // 3. 发送请求
  var xhr = creXhr()
  if (_default.type.toUpperCase() === 'GET' && _default.data) {
    _default.url += '?' + _default.data
  }
  xhr.open(_default.type, _default.url, _default.async)
  xhr.onreadystatechange = function () {
    if (xhr.status >= 200 && xhr.status < 300 && xhr.readyState === 4) {
      if (_default.dataType === 'json') {
        var res = JSON.parse(xhr.responseText)
        _default.success(res)
      } else if (_default.dataType === 'string') {
        _default.success(xhr.responseText)
      }
    }
    if (xhr.readyState === 4 && xhr.status >= 400) {
      _default.error(xhr.status)
    }
  }
  if (_default.type.toUpperCase() === 'POST') {
    xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
  }
  xhr.send(_default.data)
}

ajax的优缺点:

  • 优点:

    1.在不刷新页面的情况下与服务器通信;

    2.使用异步的方式与服务器通信,不打断用户的操作;

    3.无需重新加载整个网页,只需要与服务器进行少量的数据交换,就能够实现对网页中的某一部分进行更新,从而减少了带宽的占用。

    4、AJAX是在客户端运行的,它承载了一部分本来由服务器承担的工作,减少了大用户量下的服务器负载。

    5.基于标准化而被广泛支持的技术,不需要下载插件或者是小程序。

  • 缺点:

    1.ajax不支持浏览器的回退按钮;

    2.ajax暴露了与服务器交互的细节;

    3.ajax对搜素引擎的支持比较弱;

    4.不容易调试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值