ajax实现步骤和原理
一、什么是ajax?
ajax = 异步 javascript 和xml。
ajax是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,ajax可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 ajax)如果需要更新内容,必需重载整个网页面。
二、ajax工作原理
ajax的工作原理相当于在用户和服务器之间加了—个中间层(ajax引擎),使用户操作与服务器响应异步化。并不是所有的用户请求都提交给服务器,像—些数据验证和数据处理等都交给ajax引擎自己来做, 只有确定需要从服务器读取新数据时再由ajax引擎代为向服务器提交请求。
ajax(asynchronous javascript and xml),实现了客户端与服务器进行数据交流过程。使用技术的好处是:不用页面刷新,并且在等待页面传输数据的同时可以进行其他操作。
三、ajax的使用及实现步骤
(1) 创建xmlhttprequest对象,也就是创建一个异步调用对象.
(2) 创建一个新的http请求,并指定该http请求的方法、url及验证信息.
(3)设置响应http请求状态变化的函数.
(4)发送http请求.
(5)获取异步调用返回的数据.
(6)使用javascript和dom实现局部刷新.
ajax运行步骤与状态值说明
在ajax实际运行当中,对于访问xmlhttprequest(xhr)时并不是一次完成的,而是分别经历了多种状态后取得的结果,对于这种状态在ajax中共有5种,分别是:
0 - (未初始化)还没有调用send()方法
1 - (载入)已调用send()方法,正在发送请求
2 - (载入完成)send()方法执行完成,
3 - (交互)正在解析响应内容
4 - (完成)响应内容解析完成,可以在客户端调用了
对于上面的状态,其中“0”状态是在定义后自动具有的状态值,而对于成功访问的状态(得到信息)我们大多数采用“4”进行判断。
第一种:
通过 promise 分装的 ajax
function param(json) { var arr = []; for (var i in json) { arr, arr.push(i + "=" + json[i]) } return arr.join("&"); } function ajax(a) { return new promise(function(resolve, reject) { a = a || {}; a.type = a.type || "get"; a.data = a.data || ""; var xhr = null; // 处理兼容问题 xhr = (window.xmlhttprequest) ? new xmlhttprequest() : new activexobject("microsoft.xmlhttp"); if (a.type === "get") { a.url += "?" + param(a.data) + "&t=" + new date().gettime(); //调用open()方法并采用异步方式 xhr.open("get", a.url, true); //使用send()方法将请求发送出去 xhr.send(); } else if (a.type === "post") { xhr.open("post", a.url, true); xhr.setrequestheader("content-type", "application/x-www-form-urlencoded"); xhr.send(param(a.data)) } xhr.onreadystatechange = function() { if (xhr.readystate === 4) { if (xhr.status === 200) { resolve(json.parse(xhr.responsetext)); } else { reject("err:" + xhr.status) } } } }) }
第二种:
通过 class 构造函数分装的
ajaxclass ajax { constructor() {this.xhr = window.xmlhttprequest ? new xmlhttprequest() : new activexobject('microsoft.xmlhttp') } fn() { this.xhr.onreadystatechange = () => { if (this.xhr.readystate === 4) { if (this.xhr.status === 200) { if (responsetype === 'json') { resolve(json.parse(this.xhr.responsetext)) } else { resolve(this.xhr.responsetext) } } else { reject(new error(this.xhr.status)) } } } } get(opt) { return new promise((resolve, reject) => { let { url, async = true, params = {}, responsetype = 'json' } = opt; if (!url) { return; } url = this.formatdata(params) ? url + '?' + this.formatdata(params) : url this.xhr.open('get', url, async); this.fn(); this.xhr.send(); }) } post(opt) { return new promise((resolve, reject) => { let { url, async = true, params = {}, responsetype = 'json', paramstype = 'application/x-www-form-urlencoded' } = opt; if (!url) { return; } this.xhr.open('post', url, async); this.fn(); this.xhr.setrequestheader('content-type', paramstype) this.xhr.send(this.formatdata(params, paramstype)); }) } formatdata(params, paramstype = 'application/x-www-form-urlencoded') { if (paramstype === 'application/x-www-form-urlencoded') { return object.entries(params).map(val => val[0] + '=' + val[1]).join('&') } else { return json.stringify(params); } } }
ajax状态码说明
1:请求收到,继续处理
2:操作成功收到,分析、接受
3:完成此请求必须进一步处理
4:请求包含一个错误语法或不能完成
5:服务器执行一个完全有效请求失败*
再具体就如下:
100——客户必须继续发出请求
101——客户要求服务器根据请求转换http协议版本
200——交易成功
201——提示知道新文件的url
202——接受和处理、但处理未完成
203——返回信息不确定或不完整
204——请求收到,但返回信息为空
205——服务器完成了请求,用户代理必须复位当前已经浏览过的文件
206——服务器已经完成了部分用户的get请求
300——请求的资源可在多处得到
301——删除请求数据,重定向
302——在其他地址发现了请求数据
303——建议客户访问其他url或访问方式
304——客户端已经执行了get,但文件未变化
305——请求的资源必须从服务器指定的地址得到
306——前一版本http中使用的代码,现行版本中不再使用
307——申明请求的资源临时性删除
400——错误请求,如语法错误
401——请求授权失败
402——保留有效chargeto头响应
403——请求不允许
404——没有发现文件、查询或url
405——用户在request-line字段定义的方法不允许
406——根据用户发送的accept拖,请求资源不可访问
407——类似401,用户必须首先在代理服务器上得到授权
408——客户端没有在用户指定的饿时间内完成请求
409——对当前资源状态,请求不能完成
410——服务器上不再有此资源且无进一步的参考地址
411——服务器拒绝用户定义的content-length属性请求
412——一个或多个请求头字段在当前请求中错误
413——请求的资源大于服务器允许的大小
414——请求的资源url长于服务器允许的长度
415——请求资源不支持请求项目格式
416——请求中包含range请求头字段,在当前请求资源范围内没有range指示值,请求也不包含if-range请求头字段
417——服务器不满足请求expect头字段指定的期望值,如果是代理服务器,可能是下一级服务器不能满足请求
500——服务器产生内部错误
501——服务器不支持请求的函数
502——服务器暂时不可用,有时是为了防止发生系统过载
503——服务器过载或暂停维修
504——关口过载,服务器使用另一个关口或服务来响应用户,等待时间设定值较长
505——服务器不支持或拒绝支请求头中指定的http版本
ajax前后端数据交互–ssm
前后台数据交互均使用json。
框架ssm(spring+springmvc+mybatis)
@requestbody注解实现接收http请求的json数据,将json数据转换为java对象
@responsebody注解用于将controller的方法返回的对象,通过httpmessageconverter接口转换为指定格式的数据如:json,xml等,通过response响应给客户端
1.导包
<dependency> <groupid>com.alibaba</groupid> <artifactid>fastjson</artifactid> <version>1.2.75</version> </dependency>
2.在配置映射器和适配器时使用
<mvc:annotation-driven></mvc:annotation-driven>
它默认加载了很多格式的解析器,例如json等,不需要手动配置。
案例
前端
// 跳转 到tranferaddsub $.ajax({ url : "/tranfermixtrue", type : "post", datatype:"json", contenttype : "application/json;charset=utf-8", <!-- 向后端传输的数据 --> data : json.stringify({ id:getdate(), accuracy:parsefloat(eval(right/50)), exercises:cons, degreeofdifficulty:1 }), success:function(result) { }, error:function(result){ } });
后端
@requestmapping(value = "/tranferaddsub") public string tranferaddsub(@requestbody exercises exercises) { // 作为addsub的中转站 applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml"); exerciseserivice serivice = context.getbean("exerciseseriviceimpl", exerciseserivice.class); string jsonstring = json.tojsonstring(exercises); exercises exercisess = json.parseobject(jsonstring, exercises.class); map<string,object> map = new hashmap<string,object>(); map.put("date",exercisess.getid()); map.put("data",jsonstring); serivice.addexercise(map); return "redirect:/addsub"; } @requestmapping(value = "/tranfermuldivide") public string tranfermuldivide(@requestbody exercises exercises) { // 作为mixtrue的中转站 applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml"); exerciseserivice serivice = context.getbean("exerciseseriviceimpl", exerciseserivice.class); string jsonstring = json.tojsonstring(exercises); exercises exercisess = json.parseobject(jsonstring, exercises.class); map<string,object> map = new hashmap<string,object>(); map.put("date",exercisess.getid()); map.put("data",jsonstring); serivice.addexercise(map); return "redirect:/muldivide"; } @requestmapping(value = "/tranfermixtrue") public string tranfermixtrue(@requestbody exercises exercises) { // 作为mixtrue的中转站 applicationcontext context = new classpathxmlapplicationcontext("applicationcontext.xml"); exerciseserivice serivice = context.getbean("exerciseseriviceimpl", exerciseserivice.class); string jsonstring = json.tojsonstring(exercises); exercises exercisess = json.parseobject(jsonstring, exercises.class); map<string,object> map = new hashmap<string,object>(); map.put("date",exercisess.getid()); map.put("data",jsonstring); serivice.addexercise(map); return "redirect:/mixtrue"; }
@requestbody将传入的json数据转换位items对象,而@responsebody将return的i对象转换成json格式返回给jsp页面。
注:保证json的key和对应的pojo类的字段一致
到此这篇关于ajax实现步骤和原理的文章就介绍到这了,更多相关ajax实现步骤和原理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论