一个例子探究jQuery的Ajax应用(一)

简介:

JavaScript技能的不足致使很长一段时间对于前端交互处理望而却步,看着编程语言TOP排行榜JavaScript的热度,加上好多网站的用户体验越来越如心,这些都离不开JavaScript。

说白了,开发人员之所以多年冷落JavaScript,终究是没能驾驭了JavaScript。但是,逃避总不是办法,开发出交互很差劲的网站,后台处理在牛逼,也没法吸引用户。随着互联网和Web2.0的发展,网上冲浪再也不是简单的获取资讯,信息,更多融入了个人情感,自媒体,社区化,群体的元素,而这些元素的融入自然少不了更加人性化的交互服务。


说了这些,多源自越来越多很好体现效果的网站的诞生。


言归正传,下面的例子是一个简单的数据操作,完全是通过Ajax完成。

1.数据库表结构:

161635128.png

2.实体类:Account(参见数据库表结构)

3.数据源获取类(JDBC)

4.数据库操作CRUD

5.处理Ajax的请求的服务类ActionServlet

jQuery提供的Ajax函数如下:

162119760.png

$.ajax(options)是jQuery中Ajax的最底层实现,下面这个例子采用此方法完成。

  • 测试页面

    162339804.png

  • 代码:

    页面代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    < body >
         < center >
             < div >
                 < div >
                     < label  id = "l_a_name" >姓名:</ label >
                         < input  type = "text"  id = "a_name"  name = "a_name"  />< br  />
                     < label  id = "l_a_feeling" >心情:</ label >< br  />
                         < textarea  rows = "10"  cols = "30"  id = "a_feeling"  name = "a_feeling" ></ textarea >
                     < div >
                         < label  id = "msg" ></ label >
                     </ div >
                 </ div >
                 < div >
                     < span >
                     < button  id = "show"  name = "show"  value = "show"                  <span>< button  id = "add"  name = "add"  value = "add"                  <span>
                         < label  id = "l_a_id" >编号:</ label >< input  type = "text"  id = "a_id"  name = "a_id"  />
                         < button  id = "update"  name = "update"  value = "update"                  </span>
                     < span >
                         < button  id = "del"  name = "del"  value = "delete"                  </span>
                     < span >
                         < button  id = "query"  name = "query"  value = "query"                  </span>
                 </ div >
                 < div >
                     < span  id = "v_a_id" ></ span >
                     < span  id = "v_a_name" ></ span >
                     < span  id = "v_a_feeling" ></ span >
                     < span  id = "v_a_time" ></ span >
                 </ div >
                 < div  id = "divs"  align = "center" ></ div >
             </ div >
         </ center >
         < div >
             网址:< input  type = "text"  id = "url"  name = "url"  />
             < input  type = "button"  id = "get"  value = "加载"   />
             < div  id = "urlcontent" ></ div >
         </ div >
         < div >
             < input  id = "wether"  type = "button"   value = "获取JSON数据"  />
             < div  id = "loadMsg" >请稍等,数据正在加载...</ div >
             < div  id = "imageDiv" ></ div >
         </ div >
    </ body >

    说明:使用Ajax来处理,移除表单标签,提交按钮等元素。

  • Ajax处理:

    实现添加信息,查询所有信息,删除指定编号信息,更新指定编号信息,查询指定编号信息。

  • 代码:


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    $(document).ready( function () {
             $( "#divs" ).hide();
             $( "#urlcontent" ).hide();
             $( "#loadMsg" ).hide();
         })
         function  show() {
             $.ajax({
                         global: true ,
                         type :  'post' ,
                         url :  "control" ,
                         data : {
                             method :  'show' ,
                         },
                         success :  function (data) {
                             var  divNode = $( "#divs" );
                             divNode.html( "" );
                             if  (data !=  "null" ) {
                                 var  o = eval( "("  + data +  ")" );
                                 var  title = $( "<div>" );
                                 title
                                         .html( "|<span>编号</span>|<span>姓名</span>|<span>心情</span>|<span>发布时间</span>|" );
                                 title.appendTo(divNode);
                                 $.each(o,  function (i, n) {
                                     var  div = $( "<div>" );
                                     var  span =  "|"
                                     $.each(n,  function (pro, val) {
                                         span = span +  "<span>"  + val +  "</span>|" ;
                                     })
                                     div.html(span).appendTo(divNode);
                                 })
                                 divNode.show();
                             else  {
                                 $( "#msg" ).html( "没有数据信息" );
                             }
                         }
                     });
         }
         function  add() {
             $( "#divs" ).hide();
             var  a_name = $( "#a_name" ).val();
             var  a_feeling = $( "#a_feeling" ).val();
             if  (a_name ==  ""  || a_feeling ==  "" ) {
                 alert( "输入信息不能为空!" );
                 return ;
             }
             $.ajax({
                 type :  'post' ,
                 url :  "control" ,
                 data : {
                     method :  'add' ,
                     a_name : a_name,
                     a_feeling : a_feeling
                 },
                 success :  function (data) {
                     $( "#msg" ).html(data);
                     $( "#v_a_name" ).html(a_name);
                     $( "#v_a_feeling" ).html(a_feeling);
                 }
             });
         }
         function  update() {
             $( "#divs" ).hide();
             var  a_id = $( "#a_id" ).val();
             var  a_name = $( "#a_name" ).val();
             var  a_feeling = $( "#a_feeling" ).val();
             if  (a_id ==  ""  && a_name ==  ""  && a_feeling ==  "" ) {
                 alert( "输入编号或者信息不能为空!" );
                 return ;
             }
             $.ajax({
                 type :  'post' ,
                 url :  "control" ,
                 data : {
                     method :  'update' ,
                     a_name : a_name,
                     a_feeling : a_feeling,
                     a_id : a_id
                 },
                 success :  function (data) {
                     $( "#msg" ).html(data);
                     $( "#v_a_id" ).html(a_id);
                     $( "#v_a_name" ).html(a_name);
                     $( "#v_a_feeling" ).html(a_feeling);
                 }
             });
         }
         function  del() {
             $( "#divs" ).hide();
             var  a_id = $( "#a_id" ).val();
             if  (a_id ==  "" ) {
                 alert( "输入编号不能为空!" );
                 return ;
             }
             $.ajax({
                 type :  'post' ,
                 url :  "control" ,
                 data : {
                     method :  'delete' ,
                     a_id : a_id
                 },
                 success :  function (data) {
                     $( "#msg" ).html(data);
                 }
             });
         }
         function  query() {
             var  a_id = $( "#a_id" ).val();
             if  (a_id ==  "" ) {
                 alert( "输入编号不能为空!" );
                 return ;
             }
             $.ajax({
                         type :  'post' ,
                         url :  "control" ,
                         data : {
                             method :  'query' ,
                             a_id : a_id
                         },
                         success :  function (data) {
                             var  divNode = $( "#divs" );
                             divNode.html( "" );
                             if  (data !=  "null" ) {
                                 var  o = eval( "("  + data +  ")" );
                                 var  title = $( "<div>" );
                                 title
                                         .html( "|<span>编号</span>|<span>姓名</span>|<span>心情</span>|<span>发布时间</span>|" );
                                 title.appendTo(divNode);
                                 $.each(o,  function (i, n) {
                                     var  div = $( "<div>" );
                                     var  span =  "|" ;
                                     $.each(n,  function (pro, val) {
                                         span = span +  "<span>"  + val +  "</span>|" ;
                                     })
                                     div.html(span).appendTo(divNode);
                                 })
                                 divNode.show();
                             else  {
                                 $( "#msg" ).html( "没有数据信息" );
                             }
                         }
                     });
         }

    说明:Ajax提交的URL是对应的处理业务的Servlet程。

  • Servlet程序代码:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    package  com.ajax.test;
    import  java.io.IOException;
    import  java.util.Calendar;
    import  java.util.Date;
    import  java.util.List;
    import  javax.servlet.ServletException;
    import  javax.servlet.annotation.WebServlet;
    import  javax.servlet.http.HttpServlet;
    import  javax.servlet.http.HttpServletRequest;
    import  javax.servlet.http.HttpServletResponse;
    @WebServlet ( "/ActionServlet" )
    public  class  ActionServlet  extends  HttpServlet {
         private  static  final  long  serialVersionUID = 1L;
         private  DAO dao =  new  DAO();
         private  Account account;
         public  ActionServlet() {
             super ();
         }
         protected  void  doGet(HttpServletRequest request,
                 HttpServletResponse response)  throws  ServletException, IOException {
             doPost(request, response);
         }
         protected  void  doPost(HttpServletRequest request,
                 HttpServletResponse response)  throws  ServletException, IOException {
             response.setCharacterEncoding( "UTF-8" );
             String method = request.getParameter( "method" );
             if  (method.equals( "add" )) {
                 String a_name = request.getParameter( "a_name" );
                 String a_feeling = request.getParameter( "a_feeling" );
                 Date a_time = Calendar.getInstance().getTime();
                 account =  new  Account();
                 account.setA_name(a_name);
                 account.setA_feeling(a_feeling);
                 account.setA_time(a_time);
                 int  result = dao.add(account);
                 if  (result ==  1 ) {
                     response.getWriter().print(a_time +  " "  + a_name +  " 发布信息成功!" );
                 else  {
                     response.getWriter().print(a_time +  " "  + a_name +  " 发布信息失败!" );
                 }
             }
             if  (method.equals( "delete" )) {
                 int  a_id = Integer.parseInt(request.getParameter( "a_id" ));
                 account =  new  Account();
                 account.setA_id(a_id);
                 int  result = dao.delete(account);
                 if  (result ==  1 ) {
                     response.getWriter().print( "删除信息成功!" );
                 else  {
                     response.getWriter().print( "删除信息失败!" );
                 }
             }
             if  (method.equals( "update" )) {
                 int  a_id = Integer.parseInt(request.getParameter( "a_id" ));
                 String a_name = request.getParameter( "a_name" );
                 String a_feeling = request.getParameter( "a_feeling" );
                 Date a_time = Calendar.getInstance().getTime();
                 account =  new  Account();
                 account.setA_id(a_id);
                 account.setA_name(a_name);
                 account.setA_feeling(a_feeling);
                 account.setA_time(a_time);
                 int  result = dao.update(account);
                 if  (result ==  1 ) {
                     response.getWriter().print(a_time +  " "  + a_name +  " 更新信息成功!" );
                 else  {
                     response.getWriter().print(a_time +  " "  + a_name +  " 更新信息失败!" );
                 }
             }
             if  (method.equals( "query" )) {
                 int  a_id = Integer.parseInt(request.getParameter( "a_id" ));
                 Account account = dao.queryById(a_id);
                 if  (account !=  null ) {
                     String json = objctToJson(account);
                     StringBuilder sb= new  StringBuilder();
                     sb.append( "{'1':" );
                     sb.append(json);
                     sb.append( "}" );
                     response.getWriter().print(sb.toString());
                 else  {
                     response.getWriter().print( "null" );
                 }
             }
             if  (method.equals( "show" )) {
                 List<Account> accountList = dao.query();
                 StringBuilder sb =  new  StringBuilder();
                 sb.append( "{" );
                 for  ( int  i =  0 , j = accountList.size(); i < j; i++) {
                     Account account = accountList.get(i);
                     sb.append(i);
                     sb.append( ":" );
                     sb.append(objctToJson(account));
                     if  (i != j -  1 ) {
                         sb.append( "," );
                     }
                 }
                 sb.append( "}" );
                 response.getWriter().print(sb.toString());
             }
         }
         /**
          * 将对象信息转换为JSON格式的数据
          * @param account
          * @return
          */
         private  String objctToJson(Account account) {
             StringBuilder sb =  new  StringBuilder();
             sb.append( "{" );
             sb.append( "'a_id':'"  + account.getA_id() +  "'," );
             sb.append( "'a_name':'"  + account.getA_name() +  "'," );
             sb.append( "'a_feeling':'"  + account.getA_feeling() +  "'," );
             sb.append( "'a_time':'"  + account.getA_time() +  "'" );
             sb.append( "}" );
             return  sb.toString();
         }
    }


  • 下面是测试的效果图:

    163908535.png

    163909105.png

    至此:jQuery的Ajax底层实现操作实现了无刷新的数据库CRUD操作,整个过程在一个HTML页面中完成。

  • jQuery提供的$.get(),$.post(),load()方法是在$.ajax()的基础上进行封装,如果将$.ajax()定为第一层,那么这些方法就是第二层,$.getScript()和$.getJSON()方法就是第三层。



本文转自 secondriver 51CTO博客,原文链接:http://blog.51cto.com/aiilive/1304319,如需转载请自行联系原作者
相关文章
|
26天前
|
前端开发 JavaScript
Jquery ajax捕获错误信息
Jquery ajax捕获错误信息
12 0
|
1月前
|
JSON 缓存 前端开发
Jquery中AJAX的应用
Jquery中AJAX的应用
37 0
|
2月前
|
JSON 前端开发 JavaScript
jQuery中ajax的使用
jQuery中ajax的使用
|
2月前
|
XML JavaScript 前端开发
【Web智能聊天客服】之JavaScript、jQuery、AJAX讲解及实例(超详细必看 附源码)
【Web智能聊天客服】之JavaScript、jQuery、AJAX讲解及实例(超详细必看 附源码)
33 0
|
2月前
|
JSON 前端开发 Java
利用Spring Boot处理JSON数据实战(包括jQuery,html,ajax)附源码 超详细
利用Spring Boot处理JSON数据实战(包括jQuery,html,ajax)附源码 超详细
32 0
|
XML 开发框架 缓存
jQuery ajax - ajax()方法
jQuery ajax - ajax()方法
139 0
jQuery ajax - ajax()方法
|
Web App开发 XML JavaScript
jQuery ajax - ajax() 方法
jQuery ajax - ajax() 方法 http://www.w3school.com.cn/jquery/ajax_ajax.asp jQuery Ajax 参考手册 实例 通过 AJAX 加载一段文本: jQuery 代码: $(document).
1123 0
|
JSON 前端开发 JavaScript
JQuery中$.ajax()方法参数详解(转载)
url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址。 type: 要求为String类型的参数,请求方式(post或get)默认为get。注意其他http请求方法,例如put和       delete也可以使用,但仅部分浏览器支持。
947 0
|
XML JavaScript 前端开发
jQuery ajax - ajax() 方法
jQuery ajax - ajax() 方法: http://www.w3school.com.cn/jquery/ajax_ajax.asp   data 类型:String 发送到服务器的数据。
757 0