Ajax

什么是Ajax?

AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术。

ajax是一种浏览器异步发起请求。局部更新页面的技术。

javaScript原生Ajax请求

原生的Ajax请求,

1、我们首先要创建XMLHttpRequest 对象

2、调用open方法设置请求参数

3、调用send方法发送请求

4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="pragma" content="no-cache" />
        <meta http-equiv="cache-control" content="no-cache" />
        <meta http-equiv="Expires" content="0" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript">
            function ajaxRequest() {
//                 1、我们首先要创建XMLHttpRequest 
                var xhr = new XMLHttpRequest();
//                 2、调用open方法设置请求参数
                xhr.open("GET","ajaxServlet?action=javaScriptAjax&a="+new Date(),true);
//                 4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作。
                xhr.onreadystatechange = function() {
                    // 判断请求完成,并且成功
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        document.getElementById("div01").innerHTML = xhr.responseText;
                    } 
                }
//                 3、调用send方法发送请求
                xhr.send();
            }
        </script>
    </head>
    <body>    
        <button onclick="ajaxRequest()">ajax request</button>
        <div id="div01">
        </div>
    </body>
</html>

对应接收数据的Servlet和对应的方法:

public class AjaxServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    protected void javaScriptAjax(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("ajax请求过来了 a--" + request.getParameter("a"));
        Random random = new Random(System.currentTimeMillis());
        // 使用随机数,可以让客户端看到变化
        response.getWriter().write(
                new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    }

}

web.xml中的配置:

  <servlet>
    <servlet-name>AjaxServlet</servlet-name>
    <servlet-class>com.soyoungboy.servlet.AjaxServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>AjaxServlet</servlet-name>
    <url-pattern>/ajaxServlet</url-pattern>
  </servlet-mapping>

结果:

JQuery的Ajax请求

四个Ajax请求方法

$.ajax方法

$.get方法

$.post方法

$.getJSON方法

 

一个表单序列化方法:serialize()表单序列化方法

 

如何使用上面的五个方法:

在JQuery中和Ajax请求有关的方法有四个

$.ajax请求参数

url                                 请求的地址

type :                         请求的方式             get或post

data :                        请求的参数             string或json

success:                    成功的回调函数

dataType:                 返回的数据类型      常用json或text

 

下面的方法必须遵守参数的顺序

$.get请求和$.post请求

url:请求的URL地址

data:待发送 Key/value 参数。

callback:载入成功时回调函数。

type:返回内容格式,xml, html, script, json, text。

 

Jquery$.getJSON

url:待载入页面的URL地址

data:待发送 Key/value 参数。

callback:载入成功时回调函数。

 

表单的序列化

serialize() 方法可以把一个form表单中所有的表单项。都以字符串name=value&name=value的形式进行拼接,省去我们很多不必要的工作。

 

由于$.get、$.post和getJSON这三个方法的底层都是直接或者间接地使用$.ajax()方法来实现的异步请求的调用。所以我们以$.ajax()方法的使用为示例进行展示:

举例说明:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="pragma" content="no-cache" />
        <meta http-equiv="cache-control" content="no-cache" />
        <meta http-equiv="Expires" content="0" />
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Insert title here</title>
        <script type="text/javascript" src="script/jquery-1.7.2.js"></script>
        <script type="text/javascript">
            $(function(){
                // ajax请求
                $("#ajaxBtn").click(function(){
                    $.ajax({
                        url : "ajaxServlet", // 请求地址
                        error:function(){   // 请求失败回调
                            alert("请求失败");
                        },
                        success:function(data){ // 请求成功回调
                            alert( data );
                        },
                        type:"POST",                // 请求的方式
                        dataType:"json",            // 返回的数据类型为json对象
                        data:{                        // 请求的参数
                            action:"jqueryAjax",
                            a:12,
                            date: new Date()
                        }
                    });
                });

                // ajax--get请求
                $("#getBtn").click(function(){
                    $.get(
                        "ajaxServlet",{
                            action:"jqueryGet",
                            a:12,
                            date:new Date()
                        },function(data){alert(data);},"json"
                    );
                });
                
                // ajax--post请求
                $("#postBtn").click(function(){
                    // post请求
                    $.post(
                        "ajaxServlet", // 请求路径
                        {                // 请求参数
                            action:"jqueryPost",
                            a:12,
                            date:new Date()
                        },
                        function(data){ alert( data ) },  // 成功的回调函数
                        "text"                            // 返回的数据类型
                    );
                });

                // ajax--getJson请求
                $("#getJsonBtn").click(function(){
                    // 调用
                    $.getJSON(
                        "ajaxServlet",         // 请求路径
                        {                    // 请求参数
                            action:"jqueryGetJSON",
                            a:12,
                            date:new Date()
                        }, 
                        function(data){ alert( data ) }  // 成功的回调函数        
                    );
                });

                // ajax请求
                $("#submit").click(function(){
                    // 把参数序列化
                    var data = $("#form01").serialize();
                    alert(data);
                });
                
            });
        </script>
    </head>
    <body>
        <div>
            <button id="ajaxBtn">$.ajax请求</button>
            <button id="getBtn">$.get请求</button>
            <button id="postBtn">$.post请求</button>
            <button id="getJsonBtn">$.getJSON请求</button>
        </div>
        <br/><br/>
        <form id="form01" >
            用户名:<input name="username" type="text" /><br/>
            密码:<input name="password" type="password" /><br/>
            下拉单选:<select name="single">
                  <option value="Single">Single</option>
                  <option value="Single2">Single2</option>
            </select><br/>
              下拉多选:
              <select name="multiple" multiple="multiple">
                <option selected="selected" value="Multiple">Multiple</option>
                <option value="Multiple2">Multiple2</option>
                <option selected="selected" value="Multiple3">Multiple3</option>
              </select><br/>
              复选:
             <input type="checkbox" name="check" value="check1"/> check1
             <input type="checkbox" name="check" value="check2" checked="checked"/> check2<br/>
             单选:
             <input type="radio" name="radio" value="radio1" checked="checked"/> radio1
             <input type="radio" name="radio" value="radio2"/> radio2<br/>
             <input id="submit" type="submit" />
        </form>            
    </body>
</html>

对应的servlet代码:

public class AjaxServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    protected void javaScriptAjax(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("ajax请求过来了 a--" + request.getParameter("a"));
        Random random = new Random(System.currentTimeMillis());
        // 使用随机数,可以让客户端看到变化
        response.getWriter().write(
                new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    }
    
    protected void jqueryAjax(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("jqueryAjax请求过来了 a--" + request.getParameter("a"));
        Random random = new Random(System.currentTimeMillis());
        // 使用随机数,可以让客户端看到变化
        response.getWriter().write(
                new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    }
    
    protected void jqueryGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("jqueryGet请求过来了 a--" + request.getParameter("a"));
        Random random = new Random(System.currentTimeMillis());
        // 使用随机数,可以让客户端看到变化
        response.getWriter().write(
                new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    }
    
    protected void jqueryPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("jqueryPost请求过来了 a--" + request.getParameter("a"));
        Random random = new Random(System.currentTimeMillis());
        // 使用随机数,可以让客户端看到变化
        response.getWriter().write(
                new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    }
    
    protected void jqueryGetJSON(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("jqueryGetJSON请求过来了 a--" + request.getParameter("a"));
        Random random = new Random(System.currentTimeMillis());
        // 使用随机数,可以让客户端看到变化
        response.getWriter().write(
                new Gson().toJson(new GsonTest.Person(random.nextInt(100), "12312")));
    }

}

 

posted @ 2017-08-01 00:23  西北野狼  阅读(212)  评论(0编辑  收藏  举报