了解Ajax
Ajax
即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式、快速动态网页应用的网页开发技术,无需重新加载整个网页的情况下,能够更新部分网页的技术。
通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
发送一个Ajax请求
四个步骤:
var xhr = new XMLHttpRequest();
xhr.open('GET','./01_data.php',true); //xhr.open("请求方式","请求地址") //请求地址: 相对路径 // 绝对路径 http:// https:// ===> 开发中比较常用的方式
xhr.send(null);
// 用事件接收 level1 => 原始版本的ajax , level2 => 进阶版本的ajax // readystate ajax状态码 // change 改变 // 事件可能触发 3-4 次 // 状态码有5个 0 1 2 3 4 // 4表示成功 xhr.onreadystatechange = function(){ // 只要判定状态即可,其他的情况不考虑 if( xhr.readyState === 4){ console.log(xhr.responseText) } }
Ajax状态码
Ajax的状态码 有5个 : 0 1 2 3 4
Ajax的兼容处理
var xhr = null; if(typeof XMLHttpRequest === "function"){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
xhr.onreadystatechange = function(){ if(xhr.readyState === 4 && /^2\d{2}$/.test(xhr.status)){ console.log(xhr.responseText); } }
封装Ajax操作
ajax是异步程序,我们什么时候可以使用ajax加载回来的数据?
// ajax 兼容性良好的封装; function ajax( options ){ // 默认参数; var _default = { type : "GET", url : "", data : null, // 返回的数据类型; dataType : "text", status : null, success : function(){}, complete : function(){}, error : function(){} } // 我们会创建一些默认参数, 如果用户传入了其他数据会对默认参数进行覆盖; options = assign( _default , options ); options.type = options.type.toLowerCase(); // 如果存在context; if( isObject(options.context) ){ var callback_list = ["success","complete","error"]; // 如果老版本浏览器更新成for循环; callback_list.forEach( function( item ){ // console.log(options[item]); options[item] = options[item].bind( options.context ); }) } // 1. 创建xhr ; //创建ajax对象的兼容 var xhr = null; if(typeof XMLHttpRequest === "function"){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } // 可以简化; // 1. 如果请求方式为get,那么我们把数据拼接到url上; if(options.type === "get"){ options.url = toUrlData( options.data , options.url , options.type) } // 2. 如果请求方式为post,那么我们把数据拼接到data上; if(options.type === "post"){ options.data = toUrlData( options.data , options.url , options.type) } // 2. 根据数据进行方法的调用; xhr.open( options.type , options.url , true ) ; options.type === "post" ? xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded") : ""; // 3. 调用send方法; xhr.send( options.type=== "get" ? null : options.data ); // 4. 调用回调函数; xhr.onreadystatechange = function(){ // xhr程序运行结束; if( xhr.readyState === 4 ){ options.complete(); if( /^2\d{2}$/.test(xhr.status) ){ // 5.传递数据 // 如果需要转换成json那么我们就返回json,如果不需要原样返回; // 如果JSON.parse报错了那么我们要调用错误函数; try{ var res = options.dataType === "json" ? JSON.parse(xhr.responseText) : xhr.responseText; options.success(res); }catch(e){ options.error(e,xhr.status); } }else{ options.error("error",xhr.status); } // 策略模式调用 : if( isObject(options.status) ){ typeof options.status[xhr.status] === "function" ? options.status[xhr.status]() : ""; } } } }
Copyright © 2004-2024 Ynicp.com 版权所有 法律顾问:建纬(昆明)律师事务所 昆明市网翼通科技有限公司 滇ICP备08002592号-4