前言:ajax的神奇之处在于JavaScript 可在不重载页面的情况与 Web 服务器交换数据,即在不需要刷新页面的情况下,就可以产生局部刷新的效果。Ajax 在浏览器与 Web 服务器之间使用异步数据传输(HTTP 请求),当然也可同步,这样就可使网页从服务器请求少量的信息,而不是整个页面。Ajax使我们的项目更小、更快,更友好,在前端开发有很高的地位,也是面试题的热点。本次测试是在localhost本地环境。
1、原生ajax
(1)html前端代码get请求方式创建一个ajax实例xhr open()方法传入三个参数,第一个是请求方式(一般为get和post),第二个参数是请求地址,第三个布尔值,true代表异步,false代表同步 send发送数据(get用不上,get发送的数据一般在链接后面,所以为显式传值,形式为键值对)绑定监听函数判断状态码 xhr.responseText得到返回数据
  var xhr = new XMLHttpRequest()   xhr.open("GET","js/text.js",true)   xhr.send()            xhr.onreadystatechange = function(){  //   if(xhr.readyState === 4&& xhr.status === 200){     var data = xhr.responseText     var datas = JSON.parse(data)     console.log(datas)    }  }  控制台输出

(2)html前端代码post请求方式 post传递方式需要设置头信息,实测简单的请求不设置也是可以这里的传值是放在send()方法里面的,所以为隐式传值,其他的都和get相同
  var xhr = new XMLHttpRequest()   xhr.open("POST","js/text.js",true)   xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");   xhr.send()           xhr.onreadystatechange = function(){     if(xhr.readyState === 4&& xhr.status === 200){     var data = xhr.responseText     var datas = JSON.parse(data)     console.log(datas)    }  }控制台输出

(3)被请求js代码
{ "name":"小明", "age":24, "array":[1,51,3,4,4,6,64]}2、函数封装 这里函数封装的一个ajax方法,用的时候直接调用该方法,传入设置参数即可
参数有请求类型type,请求地址url,传入数据data(本案例无,没有也需要“”占位),请求成功返回函数success(也可多加一个失败返回函数)
(1)前端JS代码
   function Ajax(type, url, data, success){      var xhr = null; // 初始化xhr   if(window.XMLHttpRequest){ //兼容IE    xhr = new XMLHttpRequest();   } else {    xhr = new ActiveXObject('Microsoft.XMLHTTP')   }      var type = type.toUpperCase();      var random = Math.random(); //创建随机数      if(type == 'GET'){    if(data){     xhr.open('GET', url + '?' + data, true); //如果有数据就拼接    } else {     xhr.open('GET', url + '?t=' + random, true); //如果没有数据就传入一个随机数    }    xhr.send();      } else if(type == 'POST'){    xhr.open('POST', url, true);    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");    xhr.send(data);   }         xhr.onreadystatechange = function(){  // 创建监听函数    if(xhr.readyState == 4&&xhr.status == 200){      success(xhr.responseText);     }     }  }     Ajax('get', 'js/text.js', "", function(data){ //调用函数   console.log(JSON.parse(data));  });(2)被请求js代码
{ "name":"小明", "age":24, "array":[1,51,3,4,4,6,64]}控制台输出

3、Jquery中的Ajax(先引入Jquery)(1)前端简单的JS代码 jquery中的ajax是被库封装好了的,我们直接用即可,下面是简单的ajax请求,它也有很多参数,但基础的就这些了
$.ajax({   url:"./js/text.js",    type:"GET",     dataType:"json",    success:function(data){     console.log(data)   },   error:function(res){     console.log("请求失败!")   }  })(2)被请求js代码
{ "name":"小明", "age":24, "array":[1,51,3,4,4,6,64]}控制台输出

以上如有不对之处,请大家多多指正,感谢大家对武林网的支持。
新闻热点
疑难解答