Ajax第二天——JQuery的Ajax

  JQuery中的Ajax

      jQuery 对 Ajax 操作进行了封装,

    在 jQuery 中最底层的方法是 $.ajax(),

    第二层是 load(), $.get() 和 $.post(), (常用)

    第三层是 $.getScript() 和 $.getJSON()

  更详尽的介绍请参见API

  什么是回调函数:

  这里先引用知乎网友对回调的生动形容,后续概念不再赘述回调函数概念

    你到一个商店买东西,刚好你要的东西没有货,于是你在店员那里留下了你的电话,
    过了几天店里有货了,店员就打了你的电话,然后你接到电话后就到店里去取了货。
    在这个例子里,你的电话号码就叫回调函数,
    你把电话留给店员就叫登记回调函数,
    店里后来有货了叫做触发了回调关联的事件,
    店员给你打电话叫做调用回调函数,
    你到店里去取货叫做响应回调事件。
  链接:https://www.zhihu.com/question/19801131/answer/13005983
  相对正式专业的回答参见:http://www.jb51.net/article/54750.htm
 
  先来看底层的$.ajax()方法:
 
    此方法只接收一个参数,参数可能的键值对参见:http://www.runoob.com/jquery/ajax-ajax.html
  看实例:
<span style="font-size:18px;">          // 删除  
                $.ajax({  
                    type : "POST",  //提交方式  
                    url : "${pageContext.request.contextPath}/org/doDelete.action",//路径  
                    data : {  
                        "org.id" : "${org.id}"  
                    },//数据,这里使用的是Json格式进行传输  
                    success : function(result) {//返回数据根据结果进行相应的处理  
                        if ( result.success ) {  
                            $("#tipMsg").text("删除数据成功");  
                            tree.deleteItem("${org.id}", true);  
                        } else {  
                            $("#tipMsg").text("删除数据失败");  
                        }  
                    }  
                });  
</span> 

    data:传输的数据,主要方式有三种,html拼接的,json数组,form表单经serialize()序列化(见SSM-CRUD实例)的;通过dataType指定,不指定智能判断

 这里可以参见网友的:http://www.cnblogs.com/my-effort/p/6307303.html

  【更新】:ajax的其他属性设置请参见文档:http://tool.oschina.net/apidocs/apidoc?api=jquery

  例如async属性:

      ajax是异步的,不会阻塞后续代码执行,你要阻塞就改为同步的,这些都是底层的知识,所以要先学底层

$.ajax({
    async:false,
             type: 'POST'
    ...
   $.load()方法

    load() 方法是 jQuery 中最为简单和常用的 Ajax 方法, 能载入远程的 HTML 代码并插入到 DOM 中.

    它的结构是: load(url[, data][,callback]) 

    程序员只需要使用 jQuery 选择器为 HTML 片段指定目标位置, 然后将要加载的文件的 url 做为参数传递给 load() 方法即可

  testload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
    <script type="text/javascript" src="../jquery-3.1.1.min.js"></script>
    <script type="text/javascript">
    $(function(){
        $("a").click(function(){
            //使用load方法处理ajax
            var url=this.href;
            var args={"time":new Date()};
            $("#content").load(url,args);
            return false;
            });
    });
    </script>
  </head>
  
  <body>
    <a href="helloAjax.txt">hello ajax</a>
    <div id="content"></div>
  </body>
</html>
View Code

  任何一个HTML结点都可以使用load()方法来加载ajax,结点直接插入到html中

   $.get() 和 $.post()方法 

    $.get() 方法使用 GET 方式来进行异步请求.

    它的结构是: $.get(url[, data][, callback][, type]);

    $.get() 方法的回调函数只有两个参数: data 代表返回的内容, 可以是 XML 文档, JSON 文件, HTML 片段等;

    textstatus 代表请求状态, 其值可能为: succuss, error, notmodify, timeout 4 种.

    注意type若自动填写了会严格强制按照指定类型执行,一般的Jquery的ajax是智能判断的

    $.get() 和 $.post() 方法时 jQuery 中的全局函数, 而 load() 等方法都是对 jQuery 对象进行操作的方法,两个方法类同,不再赘述

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  <script type="text/javascript" src="../jquery-3.1.1.min.js"></script>
  <script type="text/javascript">
      $(function(){
        $("a").click(function(){
            var url=this.href;
            var args={"time":new Date()};
            $.get(url,args,function(data){
                var name=$(data).find("name").text();
                var email=$(data).find("email").text();
                var website=$(data).find("website").text();
                $("#details").empty()
                        .append("<h2><a href='mailto:"+email+"'>"+name+"</a></h2>")
                        .append("<a href='"+website+"'>"+website+"</a>");
                });
            return false;

        });
      })          
  </script>
  </head>
  
  <body>
    <h1>People</h1>
    <ul>
        <li><a href="files/andy.xml">Andy</a></li>
           <li><a href="files/richard.xml">Richard</a></li>
           <li><a href="files/jeremy.xml">Jeremy</a></li>
    </ul>
    <div id="details"></div>
  </body>
</html>
View Code

 //其中的function是回调函数,当响应结束时,回调函数被触发,响应结果在data中

  testgetJSON 测试JSON数据格式 
  注:

    "{result:{\"success\":\"true\",\"meg\":\"success\"}}"
    "{\"success\":true,\"mesg\":\"success\"}"

  对比两条JSON字符串,其中bool值是不需要加引号的,并且指定了JSON的type后,JSON格式变得更加严格,单引号或者不加引号都是严禁的。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
<script type="text/javascript" src="../scripts/jquery-1.4.2.js"></script>
  <script type="text/javascript">
  //url:ajax请求的目标url
  //args:传递的参数:json类型
  //data:ajax响应成功后的数据,可能是xml,html,json
      $(function(){
        $("a").click(function(){
            var url=this.href;
            var args={"time":new Date()};
            $.getJSON(url,args,function(data){
                var name=data.person.name;
                var email=data.person.eamil;
                var website=data.person.website;
                $("#details").empty()
                        .append("<h2><a href='mailto:"+email+"'>"+name+"</a></h2>")
                        .append("<a href='"+website+"'>"+website+"</a>");
                });
            return false;

        });
      })          
  </script>
  </head>
  
  <body>
    <h1>People</h1>
    <ul>
        <li><a href="files/andy.js">Andy</a></li>
           <li><a href="files/richard.js">Richard</a></li>
           <li><a href="files/jeremy.js">Jeremy</a></li>
    </ul>
    <div id="details"></div>
  </body>
</html>
View Code

 

   

  更多实例请参见jQuery Ajax的API Ajax 部分http://tool.oschina.net/apidocs/apidoc?api=jquery

 

  典型应用举例
  1.校验用户名是否被占用
  jsp页面:index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
    <!-- 注意此处src的写法 -->
    <script type="text/javascript" src="${pageContext.request.contextPath }/jquery-3.1.1.min.js"></script>
    <script type="text/javascript">
        /*
            导入库
            获取name结点
            为结点添加change()事件
            获取结点的value值,进行校验
            此处直接返回HTML片段,在客户端浏览器可以查看如红色加粗提示效果
        */
        $(function(){
            $(":text[name='username']").change(function(){
                var val = $(this).val();
                val = $.trim(val);
                if(val != ""){
                    var url = "${pageContext.request.contextPath }/validateUsername";
                    var args = {"username":val,"time":new Date()};
                    $.post(url,args,function(data){
                        $("#message").html(data);
                    });
                }
            });
        })
    </script>
 
</head>
  
  <body>
    <form action="" method="post">
        UserName:<input type="text" name="username"/>
        <br/>
        <div id="message"></div>
        <br/>
        <input type="submit" value="Submit"/>
    </form>
  </body>
</html>
View Code

  //注意点:项目名的写法,servlet的路径的匹配

  servlet页面 

package cn.servlet;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class validataUsernameServlet
 */
public class validataUsernameServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public validataUsernameServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<String> list = Arrays.asList("aaa","bbb","ccc");
        String username = request.getParameter("username");
        String result = null;
        if(list.contains(username)){
            result = "<font color='red'>该用户名已经被使用</font>";
        }else{
            result = "<font color='green'>该用户名可以使用</font>";
        }
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().print(result);
    }

}
View Code

  //注意点:创建servlet时的路径写法,设置编码

   2.添加商品
   jsp页面:index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'index.jsp' starting page</title>
  <!-- 
  1.获取当前页面所有的a节点,并为每一个a节点都添加onclick响应函数,同时取消其默认行为
  2.准备发送Ajax请求:Url(a节点的href属性值);args(时间戳)
  3.响应为一个json对象,包括:bookName,totalBookNumber,totalMoney
  4.把对应的属性添加到对应的位置
   -->
   
   <script type="text/javascript" src="${pageContext.request.contextPath}/jquery-3.1.1.min.js"></script>
   <script type="text/javascript">
           $(function(){
               var isHasCart="${sessionScope.sc==null}";
                  //alert(isHasCart);
                  if(isHasCart){
                $("#cartstatus").hide();
                     }else{
                        $("#cartstatus").show();
                        $("#bookName").text("${sessionScope.sc.bookName}");
                $("#totalBookNumber").text("${sessionScope.sc.totalBookNumber}");
                $("#totalMoney").text("${sessionScope.sc.totalMoney}");
                     }
               $("a").click(function(){
                   $("#cartstatus").show();
                   var url = this.href;
                   var args = {"time":new Date()}
                   $.getJSON(url,args,function(data){
                       $("#bookName").text(data.bookName);
                    $("#totalBookNumber").text(data.totalBookNumber);
                    $("#totalMoney").text(data.totalMoney);
                   });
                   return false;
               });
           })
   
   </script>
  </head>
  
  <body>
      <div id="cartstatus">
          您已经将&nbsp;<span id="bookName"></span>&nbsp;加入到购物车中,
          购物车中的书有&nbsp;<span id="totalBookNumber"></span>&nbsp;本,
          总价格&nbsp;<span id="totalMoney"></span>&nbsp;钱
    </div>      <br/><br/>
    Java<a href="${pageContext.request.contextPath}/AddToCart?id=Java&price=300">加入购物车</a>
    <br/><br/>
    Oracle<a href="${pageContext.request.contextPath}/AddToCart?id=Oracle&price=200">加入购物车</a>
    <br/><br/>
    Struts2<a href="${pageContext.request.contextPath}/AddToCart?id=Struts2&price=100">加入购物车</a>
    <br/><br/>
  </body>
</html>
View Code

  servlet页面

package cn.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.bean.ShoppingCart;

/**
 * Servlet implementation class AddToCartServlet
 */
public class AddToCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddToCartServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        //1.获取请求参数 id,price
        String bookName = request.getParameter("id");
        int price = Integer.parseInt(request.getParameter("price"));
        //2.获取购物车对象
        HttpSession session = request.getSession();
        ShoppingCart sc = (ShoppingCart) session.getAttribute("sc");
        //session中无购物车则创建一辆车给他,并放在session中
        if(sc == null){
            sc = new ShoppingCart();
            session.setAttribute("sc", sc);
        }
        //3.把点击的选项加入到购物车中
        sc.addToCart(bookName, price);
        //4.准备响应的json对象
        StringBuilder sb = new StringBuilder();
          sb.append("{")
            .append("\"bookName\":\""+bookName+"\"")
            .append(",")
            .append("\"totalBookNumber\":"+sc.getTotalBookNumber())
            .append(",")
            .append("\"totalMoney\":"+sc.getTotalMoney())
            .append("}");
        //5.响应json对象
          response.setContentType("text/javascript");
          response.getWriter().print(sb.toString());
    }

}
View Code

  ShoppingCart

package cn.bean;

import java.util.HashMap;
import java.util.Map;

public class ShoppingCart {

    //存放shoppingcartitem的map 键:书名 值:shoppingcartitem对象
    private Map<String, ShoppingCartItem> items=new HashMap<String, ShoppingCartItem>();
    private String bookName;
    public void addToCart(String bookName,int price){
        this.bookName=bookName;
        if(items.containsKey(bookName)){
            ShoppingCartItem item=items.get(bookName);
            item.setNumber(item.getNumber()+1);
        }else{
            ShoppingCartItem item=new ShoppingCartItem();
            item.setBookName(bookName);
            item.setPrice(price);
            item.setNumber(1);
            items.put(bookName, item);
        }
    }
    public int getTotalBookNumber(){
        int total=0;
        for(ShoppingCartItem item:items.values()){
            total+=item.getNumber();
        }
        return total;
    }
    public int getTotalMoney(){
        int money=0;
        for(ShoppingCartItem item:items.values()){
            money+=item.getNumber()*item.getPrice();
        }
        return money;
    }
    public String getBookName() {
        return bookName;
    }
}
View Code

  ShoppingCartItem

package cn.bean;

public class ShoppingCartItem {

    private int number;
    private String bookName;
    private int price;
    public int getNumber() {
        return number;
    }
    public void setNumber(int number) {
        this.number = number;
    }
    public String getBookName() {
        return bookName;
    }
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    
}
View Code

  使用Jackson后的servlet:(Jackson简单入门见另一篇随笔)

package cn.ajax.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.codehaus.jackson.map.ObjectMapper;

import cn.itcast.beans.ShoppingCart;

public class AddToCart extends HttpServlet {

    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1.获取请求参数 id,price
        String bookName=request.getParameter("id");
        int price=Integer.parseInt(request.getParameter("price"));
        System.out.println(bookName);
        //2.获取购物车对象
        HttpSession session=request.getSession();
        ShoppingCart sc=(ShoppingCart) session.getAttribute("sc");
        if(sc==null){
            sc=new ShoppingCart();
            session.setAttribute("sc", sc);
        }
        //3.把点击的选项加入到购物车中
        sc.addToCart(bookName, price);
        //4.准备响应的json对象
//        StringBuilder result=new StringBuilder();
//        result.append("{")
//        .append("\"bookName\":\""+bookName+"\"")
//        .append(",")
//        .append("\"totalBookNumber\":"+sc.getTotalBookNumber())
//        .append(",")
//        .append("\"totalMoney\":"+sc.getTotalMoney())
//        .append("}");
        ObjectMapper mapper=new ObjectMapper();
        String result=mapper.writeValueAsString(sc);
        System.out.println(result);
        //5.响应json对象
        response.setContentType("text/javascript");
        //response.getWriter().print(result.toString());
        response.getWriter().print(mapper.writeValueAsString(sc));
    }

}
View Code

   结果演示:

 

posted @ 2017-05-19 20:25  ---江北  阅读(273)  评论(0编辑  收藏  举报
TOP