ajax专题(李强)01-ajax基本操作、ajax传递参数,ajax设置请求头,服务器端响应json请求,ajax的ie缓存问题,网络请求超时与异常处理,手动取消网络发送,重复发送请求的处理

1、ajax基本概念和基本操作

ajax基本对象xhr是ajax的XMLHttpRequest类的对象
readyState是xhr对象的属性,标识状态 有0、1、2、3、4个属性值
//0:未初始化,标识最开始的状态,初始状态就是0
//1:open方法调用完毕
//2:send方法调用完毕
//3:服务端返回了部分结果
//4:服务端返回了全部结果

后端代码
1、入口页面
app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// module.exports = app;
app.listen(3000,()=>{
  console.log('服务器启动成功,监听在3000端口')
})

2、路由页面
router/index.js

var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/test', function(req, res, next) {
  //设置响应头,允许跨域
  res.setHeader('Access-Controll-Allow-Origin','*')
  res.send({
    message:'测试响应信息',
    status:1,
    data:{
      name:'zhangsan',
      age:34,
      address:'beijing'
    }
  });
});
router.post('/test',function(req,res,next){
  //设置响应头,允许跨域
  res.setHeader('Access-Controll-Allow-Origin','*')
  res.send({
    message:'测试post请求',
    status:1,
    data:{
      name:'zhangsan',
      age:34,
      address:'beijing'
    }
  });
})

module.exports = router;
2、ajax传递参数

发送get请求

<script>
  $('#send').mouseover(function(){
    //创建ajax
    const xhr=new XMLHttpRequest()

    xhr.open('get','http://localhost:3000/test?username=zhangsan&age=34')
    xhr.send()
    //处理服务器端返回的结果
    xhr.onreadystatechange=function(){
      //readyState是xhr对象的属性,标识状态 有0、1、2、3、4个属性值
      //0:未初始化,标识最开始的状态,初始状态就是0
      //1:open方法调用完毕
      //2:send方法调用完毕
      //3:服务端返回了部分结果
      //4:服务端返回了全部结果
      if (xhr.readyState==4){
        //判断返回状态码
        if (xhr.status>=200 && xhr.status<300){
          //在这里处理返回的结果,行,头,空行,体
          console.log(xhr.status)//状态码
          console.log(xhr.statusText)//状态字符串
          console.log(xhr.getAllResponseHeaders())//所有的响应头
          console.log(xhr.response)//响应体
          $('#content').text(xhr.response)
        }
      }
    }

  })


</script>

发送post请求

<script>
  $('#content').mouseover(function(){
    //创建ajax
    const xhr=new XMLHttpRequest()
    xhr.open('post','http://localhost:3000/test')
    xhr.send()
    //处理服务器端返回的结果
    xhr.onreadystatechange=function(){
      if (xhr.readyState==4){
        //判断返回状态码
        if (xhr.status>=200 && xhr.status<300){
          $('#content').text(xhr.response.message)
        }
      }
    }

  })


</script>

3、ajax设置请求头信息
 xhr.setRequestHeader(
      'Content-type',
      'application/x-www-form-urlencoded')
    xhr.send('a=100&b=200&c=300')

完整代码

<script>
  $('#content').mouseover(function(){
    //创建ajax
    const xhr=new XMLHttpRequest()
    xhr.open('post','http://localhost:3000/test')

    //设置请求他欧
    //Content-type:请求类型

    xhr.setRequestHeader(
      'Content-type',
      'application/x-www-form-urlencoded')
    xhr.send('a=100&b=200&c=300')
    // xhr.send('a:100&b:200&c:300')

    //处理服务器端返回的结果
    xhr.onreadystatechange=function(){
      if (xhr.readyState==4){
        //判断返回状态码
        if (xhr.status>=200 && xhr.status<300){
          $('#content').text(xhr.response)
        }
      }
    }

  })


</script>

4、服务端响应json请求

需要设置自动转化,虽然可以手动转换,但是并不建议
xhr.responseType=‘json’

<script>
  $('#send').click(function(){

    const xhr=new XMLHttpRequest()
    //设置json格式转换,如果使用手动方式转换,则不需要这一项
    xhr.responseType='json'

    xhr.open('get','http://localhost:3000/test')
    xhr.send()
    xhr.onreadystatechange=function () {
      if (xhr.readyState===4){
        if (xhr.status>=200 && xhr.status<300){
          //手动数据转换
          //let data_json=JSON.parse(xhr.response)
          // console.log(data_json)
          // $('#content').html(data_json.data.name)
          console.log(xhr.response)
          $('#content').html(xhr.response.data.name)
        }
      }
    }
  })


</script>
5、ajax的ie缓存问题

ie浏览器对于数据会优先提取缓存的数据因此需要修改请求地址,实际上就是给请求地址加上一个时间参数

    xhr.open('get','http://localhost:3000/test?t='+Date.now())

6、网络请求超时与异常处理
//超时时间设置
    xhr.timeout=2000
    //超时回调
    xhr.ontimeout=function(){
      console.log('网络超时了')
    }
    //网络异常回到
    xhr.onerror=function(){
      console.log('网络异常了')
    }

完整代码

<script>
  $('#send').click(function(){
    const xhr=new XMLHttpRequest()
    //超时时间设置
    xhr.timeout=2000
    //超时回调
    xhr.ontimeout=function(){
      console.log('网络超时了')
    }
    //网络异常回到
    xhr.onerror=function(){
      console.log('网络异常了')
    }
    xhr.open('get','http://localhost:3000/delay?t='+Date.now())
    xhr.send()
    xhr.onreadystatechange=function () {
      if (xhr.readyState===4){
        if (xhr.status>=200 && xhr.status<300){
          $('#content').html(xhr.response)
        }
      }
    }
  })


</script>
7、手动取消网络发送

xhr.abort()

8、重复发送请求

当用户疯狂发送相同请求的时候,先看看请求是否重复,如果重复,则取消前次请求,发送本次请求

<script>
  //对请求标注个表示变量,表示是否在发送ajax请求
  let isSending=false
  let xhr_qlobal;
  $('#send').click(function(){
    if (isSending){
      xhr_qlobal.abort()
    }
    xhr_qlobal=new XMLHttpRequest()

    isSending=true
    xhr_qlobal.open('get','http://localhost:3000/test')
    xhr_qlobal.send()
    xhr_qlobal.onreadystatechange=function () {
      if (xhr_qlobal.readyState===4){
        isSending=false
        $('#content').html(xhr_qlobal.response)
      }
    }
  })


</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值