Ajax的async属性(通过ajax请求分页查询实例)
2014-01-17 13:18
525 查看
jQuery.ajax( [settings ] )的官方解释为:
async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous
requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding
methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
(默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
通过dhtmlxgrid的ajax请求加载后台分页数据实例看看:
jsp页面效果:(所有引入文件略)
JavaScript grid实现:
上面的function loadgrid_no(index)函数中如果没有async: false, 可能会导致在grid未加载的情况下,执行success之后的代码(即 $("#grid_invoices").css("height","300px");之后的代码),导致未加载数据时执行了后面的代码。有时会出现如下结果:
![](http://img.blog.csdn.net/20131202235500375)
因为没有async: false,,此时默认为异步处理,此时可能未加载完成数据,就进行后面的代码执行,判断后就会return。但是如果代码中加入了async: false,则表示同步,等到success执行结束之后才会执行后面的代码,效果肯定如下所示:
![](http://img.blog.csdn.net/20131202235853343)
分页效果实现的后台代码:
默认情况下,请求总会被发出去,但浏览器有可能从他的缓存中调取数据。要禁止使用缓存的结果,可以设置cache参数为false。如果希望判断数据自从上次请求后没有更改过就报告出错的话,可以设置ifModified为true。
Ajax的第一个字母是asynchronous的开头字母,这意味着所有的操作都是并行的,完成的顺序没有前后关系。$.ajax()的async参数总是设置成true,这标志着在请求开始后,其他代码依然能够执行。强烈不建议把这个选项设置成false,这意味着所有的请求都不再是异步的了,这也会导致浏览器被锁死。
async (default: true)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous
requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding
methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().
(默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。注意,同步请求将锁住浏览器,用户其它操作必须等待请求完成才可以执行。
通过dhtmlxgrid的ajax请求加载后台分页数据实例看看:
jsp页面效果:(所有引入文件略)
<div id="pagination" style="position: relative;float:right"></div> <div style="margin-top: 10px;margin-left:100px;"> <input type="button" id="recede_charge_btn" class="btn01" onclick="doSure()" value="确定" /> <input type="button" id="close_btn" class="btn01" onclick="doClose()" value="关闭" /> </div>
JavaScript grid实现:
var grid_invoices; grid_invoices = new dhtmlXGridObject('grid_invoices'); grid_invoices.setImagePath("dhtmlxGrid/codebase/imgs/"); grid_invoices.setHeader("发票号码,实收金额,收费日期"); grid_invoices.setInitWidths("110,70,220"); grid_invoices.setColAlign("center,center,center"); grid_invoices.setColTypes("ro,ro,ro"); grid_invoices.setSkin("dhx_custom"); grid_invoices.init(); loadCount_no();JavaScript分页效果实现:
function loadCount_no(){ var cardno = $("#search_value").val(); $.ajax({ async:false, cache:false, type:"POST", url:"clc/getInvoicesCount.htm", data:"cardno="+cardno, error:function(){ alert("服务器内部错误!"); }, success:function(data){ if(data=='fail'){ alert("获取数据失败!"); }else{ createPagination_no(data); } } }); } var pageSize = 10; var pageIndex = 0; function createPagination_no(pageCount){//创建分页标签,pageCount为返回的记录数 if(pageCount==0){ pageCount=0; } //分页,pageCount是总条目数,这是必选参数,其它参数都是可选 $("#pagination").pagination(pageCount, { callback: pageCallback_no, prev_text: '上一页', //上一页按钮里text next_text: '下一页', //下一页按钮里text items_per_page: pageSize, //显示条数 num_display_entries: 6, //连续分页主体部分分页条目数 current_page: pageIndex, //当前页索引 num_edge_entries: 2 //两侧首尾分页条目数 }); } function pageCallback_no(index, jq){//翻页回调 pageIndex = index; //当前页索引 loadgrid_no(index); return false; } //条件查询获取当前页未处理报表 function loadgrid_no(index){ var cardno = $("#search_value").val(); if(index!=0){ index = pageIndex; } $.ajax({ type:"GET", url:"clc/getInvoices.htm?cardno="+cardno+"&index="+index+"&size="+pageSize, cache: false, async: false, error:function(){ // alert("没有该病人记录!"); }, success: function(reply){ if(reply=="fail"){ alert("没有该病人记录!"); }else{ var jsons=eval("("+reply+")"); grid_invoices.clearAll(); for(var i=0;i<jsons.length;i++){ grid_invoices.addRow( jsons[i].invoiceid, [ jsons[i].invoiceno, jsons[i].totalcost_a, jsons[i].chgdate ], i ); } } } }); $("#grid_invoices").css("height","300px"); grid_invoices.setSizes(); if(grid_invoices.getRowsNum()==0){ alert("未找到该病人可退费发票!"); return; } $.blockUI({message: $('#hidden_chgRcd'),css:{width:'410px',height:'400px',border:'0px solid #aaa'},overlayCSS:{backgroundColor: '#CCCCCC'}}); }
上面的function loadgrid_no(index)函数中如果没有async: false, 可能会导致在grid未加载的情况下,执行success之后的代码(即 $("#grid_invoices").css("height","300px");之后的代码),导致未加载数据时执行了后面的代码。有时会出现如下结果:
因为没有async: false,,此时默认为异步处理,此时可能未加载完成数据,就进行后面的代码执行,判断后就会return。但是如果代码中加入了async: false,则表示同步,等到success执行结束之后才会执行后面的代码,效果肯定如下所示:
分页效果实现的后台代码:
@RequestMapping(value = "/getInvoicesCount") public void getInvoicesCount(HttpServletRequest request,HttpServletResponse response) throws Exception{ String patientid = (String)request.getParameter("cardno"); Bas_hospitals basHospitals = (Bas_hospitals)request.getSession().getAttribute("login_hospital"); String hosnum = basHospitals.getHosnum(); String nodecode = basHospitals.getNodecode(); DBOperator db = new DBOperator(); response.setContentType("text/JSON;charset=utf-8"); PrintWriter pw = response.getWriter(); try{ String sql = "select count(*) count from chg_invoice t " + "where t.patientid=? and t.hosnum=? and t.invoiceid not in (select t2.invoiceid from chg_invoice_cancel t2) and t.invoiceno is not null and t.clcorinp ='门诊' order by t.chgdate desc"; List<Map<String, Object>> list = db.find(sql, new Object[]{patientid,hosnum}); pw.print(list.get(0).get("count")); db.commit(); }catch(Exception e){ e.printStackTrace(); db.rollback(); pw.print("fail"); }finally{ db.freeCon(); pw.flush(); pw.close(); } } @RequestMapping(value = "/getInvoices") public void getInvoices(HttpServletRequest request,HttpServletResponse response) throws Exception{ String patientid = (String)request.getParameter("cardno"); int Pagesize = Integer.parseInt(request.getParameter("size")); int index = Integer.parseInt(request.getParameter("index")); Bas_hospitals basHospitals = (Bas_hospitals)request.getSession().getAttribute("login_hospital"); String hosnum = basHospitals.getHosnum(); String nodecode = basHospitals.getNodecode(); DBOperator db = new DBOperator(); response.setContentType("text/JSON;charset=utf-8"); PrintWriter pw = response.getWriter(); try{ String pagingSql1 = "select OHYEAH.* from (select OHNO.*,rownum no from ("; // 用于分页// 段1 String pagingSql2 = ") OHNO where rownum <= ?) OHYEAH where no > ?"; // 用于分页段2 String sql = "select t.invoiceid,t.invoiceno,t.totalcost_a,to_char(t.chgdate,'yyyy-mm-dd') chgdate " + "from chg_invoice t " + "where t.patientid=? and t.hosnum=? and t.invoiceid not in (select t2.invoiceid from chg_invoice_cancel t2) and t.invoiceno is not null and t.clcorinp ='门诊' order by t.chgdate desc"; List<Map<String, Object>> list = db.find(pagingSql1+sql+pagingSql2, new Object[]{patientid,hosnum,Pagesize*index+Pagesize,Pagesize*index}); JSONArray json = JSONArray.fromObject(list); //system.out.println(json); pw.print(json); }catch(Exception e){ e.printStackTrace(); db.rollback(); pw.print("fail"); }finally{ db.freeCon(); pw.flush(); pw.close(); } }
默认情况下,请求总会被发出去,但浏览器有可能从他的缓存中调取数据。要禁止使用缓存的结果,可以设置cache参数为false。如果希望判断数据自从上次请求后没有更改过就报告出错的话,可以设置ifModified为true。
Ajax的第一个字母是asynchronous的开头字母,这意味着所有的操作都是并行的,完成的顺序没有前后关系。$.ajax()的async参数总是设置成true,这标志着在请求开始后,其他代码依然能够执行。强烈不建议把这个选项设置成false,这意味着所有的请求都不再是异步的了,这也会导致浏览器被锁死。
相关文章推荐
- ASP.NET easyUI--datagrid 通过ajax请求ASP.NET后台数据的分页查询
- query ajax json 通过后台代码(查询数据库)绑定html控件select 下拉框实例
- 通过Ajax请求动态填充页面数据的实例
- mysql通过“延迟关联”进行limit分页查询优化的一个实例
- AJAX请求中增加async属性的作用
- MyBatis代码实例系列-10:MyBatis通过PageHelper插件实现分页查询
- Jquery通过ajax请求NodeJS返回json数据实例
- 通过Ajax+jquery实现的动态增加一组查询条件的实例
- 前端通过Ajax请求从后台返回数据到页面显示,实现分页功能
- 使用ajax进行分页查询因连接池耗尽导致请求被挂起(备忘)
- laravel vue控件通过axios向api发起请求,获取分页实例对象reponse.data.data
- Ajax请求中的async属性
- Ajax异步请求实例
- 如何通过禁用按钮避免jQuery.ajax重复请求
- ajax异步请求实例
- 通过fetchXml 实现分页查询
- oracle,mysql,SqlServer三种数据库的分页查询的实例
- SQLserver分页查询实例
- spring,springmvc,mybatits集成实例--后台分页查询
- ajax请求嵌套多层json数据实例