Ajax

一、原生Ajax

  1.什么是Ajax?

  • Ajax的全称是Asynchronous JavaScript and XML(异步的JavaScript和XML);
  • Ajax能在不刷新整个网页的情况下,请求服务器数据更新局部内容;
  • 能实现局部刷新,大大降低了资源浪费;
  • 传统网页(不使用ajax)如果更新内容,需要刷新整个页面。

 2. 实现步骤:

   (1). 创建XMLHttpRequest对象

let xhr = new XMLHttpRequest();

   (2). 配置请求信息

xhr.open(method,url,async); 

   method:请求方式,GET或POST;

   url:请求地址,例如:https://hello.com/api/pc/coupon/getCouponListByCustIdAndStatus;

   async:是否异步请求,true异步请求(默认),false同步请求。

  (3). 发送请求

  GET:

xhr.send();    //get不传参,参数拼接在url后面

  POST:

xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");   //设置请求头
xhr.send("user=张三&pass=123");  //post需传请求参数

  (4). 监听状态变化,执行相应操作

xhr.onreadystatechange = function(){  //xhr.readyState改变时触发
  if(xhr.readyState === 4 && xhr.status === 200) {
     console.log(xhr.responseText);  //请求成功,作为响应主体被返回的文本
 }
}

  xhr.readyState:保存了xhr自身的状态

    0:请求未初始化

    1:服务器连接已建立

    2:请求已接收

    3:请求处理中

    4:请求完成,且响应已就绪

  xhr.status: 响应的http状态码

二、jQuery中的Ajax  

 jQuery.ajax()参数:

   url:请求地址

   type:请求类型,GET或POST

   dataType:预期服务器返回的数据类型,一般设置为json

   data:一个对象,发送到服务器的数据

   contentType:发送数据到服务器时所使用的内容类型,默认是:"application/x-www-form-urlencoded"。

   cache:默认true,第一次请求完成后,再次请求时,如果参数和url不变,会读取缓存中的数据,不去请求服务器的数据;false,禁用缓存

   success:请求成功后的回调函数

   error:请求失败后的回调函数

   beforesend:请求发送前执行的回调函数

   complete:请求完成时执行的回调函数

$.ajax({
   url:"https://hello.com/coupon/getCouponListByCustIdAndStatus",
   type:"POST",
   cache:false,
   dataType:"json",
   data:{
      username:"张三",
      password:123
   },
   success:function(data){
      console.log(data)
   },
   error:function(){
      console.log("通讯错误,请重试。")
   }
})
原文地址:https://www.cnblogs.com/crackedlove/p/10045597.html