day6 - jquery Ajax异步请求处理

主要内容
1.什么是AJAX
2. jQuery.ajax(url, [settings])函数
3. JSON数据交换格式
4. 服务器端处理ajax请求及工具应用
5. 其他jQuery ajax处理工具应用
6. jQuery.get(url, [data], [callback], [type])函数
7. jQuery.post(url, [data], [callback], [type])函数

1. 什么是AJAX

局部页面刷新。AJAX是异步的javaScript和xml数据处理技术。AJAX是利用浏览器对象XMLHttpRequest实现对远程服务器程序发出异步(也可以是同步)请求并从服务器返回数据后使用JavaScript在客户端处理返回数据从而局部更新web资源页面的一种技术。

AJAX处理数据的优势在于根据实际需要选择同步或异步提交到服务器的请求,在异步请求过程中用户无需等待整个页面全部刷新就可以在页面中处理数据,此方式对于传统同步提交(通常是form提交数据)更具有灵活性,增强用户丰富的页面处理体验并大大提高请求效率。

2. jQuery.ajax(url, [settings]) 核心函数

通过HTTP请求加载并返回远程数据(如果需要),jQuery最底层AJAX实现,此函数返回其创建的XMLHtmlRequest对象. 简写为$.ajax(url, [settings]),此函数向服务器发出异步或同步请求并在合适时机调用预定义的JS函数。

在不带参数情况下只返回XMLHtmlRequest对象,它不会向任何服务器程序发出实际请求,如果要设置参数也可以通过$.ajaxSetup()函数来全局设置。

Setting之中的参数设置

2.1 jQuery AJAX回调函数

回调函数是ajax请求过程中某个阶段被执行的功能模块,主要包含以下的回调函数:
beforeSend: 在发送请求之前调用,并且传入一个XMLHttpRequest作为参数,此函数是最先被调用的回调函数
error: 在请求出错时调用,传入XMLHttpRequest对象,描述错误类型的字符串以及一个异常对象
dataFilter: 在请求成功之后调用,传入返回的数据以及"dataType"参数的值,并且必须返回新的数据(可能是处理过的)传递给success回调函数,此函数总是在success函数之前执行
success: 当请求成功之后调用,传入返回后的数据,以及包含成功代码的字符串,通常在此函数中处理返回的数据
complete: 当请求完成后调用这个函数,无论成功或失败,传入XMLHttpRequest对象,以及一个包含成功或错误代码的字符串

代码示例

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>jQuery实现Ajax请求处理</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
      /*是一个异步请求,网页的局部刷新*/
        function doAjax() {
          $.ajax({
            url:'FirstAjaxServlet', //ajax请求服务器的url
            success:function (data,mess) { //如果请求成功,服务器成功返回,则执行此函数
              console.log("执行success回调函数");
              alert(data);
              /*alert(data);
              alert(mess);*/
            },
            dataFilter:function(data){
              console.log("执行dataFilter回调函数,此函数用来对服务器返回的数据进行过滤");
              if (data === 'hello');
              return 'hi';
            },
            beforeSend: function(data){
              console.log("执行beforeSend回调函数,此回调函数最先被执行");
            },
            error:function (err) { //如果Ajax请求过程出现错误,则执行此回调函数
              alert(err+"This is an error, please try it later");
              console.log("请求中出现错误回调此函数");
            },
            complete:function () {
              console.log("Ajax请求最后回调的函数")
            }
          });
        }
    </script>

  </head>
  <body bgcolor="#87ceeb">
    <input value="" type="text"/><br>
      <button onclick="doAjax()">第一个基于jQuery的Ajax请求</button>
      <a href="UseJsonLibConvertJsonAndJavaObjectServlet">测试java对象转化为json字符串</a>

  </body>
</html>
2.1 执行成功的回调函数
2.2 执行失败的回调函数的执行顺序

2.2 jQuery AJAX数据返回类型

dataType字符串类型参数设置 期待请求服务器成功返回的数据类型


2.3 jQuery AJAX数据返回类型

2.3 jQuery AJAX主要参数URL

url: 向远程服务器提交请求的url字符串,通常此参数是必需的。url的字符串也可以在其后面使用?参数名=值&参数名=值得方式追加提交到服务器得请求参数

2.4 jQuery AJAX主要参数async

async: boolean类型参数,设定请求方式是异步的(true)还是同步的(false),默认值为true

2.5 jQuery AJAX主要参数cache

cache: boolean类型参数,设置是否缓存页面数据,默认值为true缓存数据,cache缓存只对get方式请求起作用而对post方式无效,注意在dataType为script和json时默认为false

2.6 jQuery AJAX主要参数type

type:字符类型参数,设置请求方法格式,通常支持以下值:
get: http get方式请求,参数将暴露在请求url中
post: http post方式请求,隐藏参数传递
put:
delete:
put和delete多数浏览器不支持

示例:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>jQuery实现Ajax请求处理</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        var res = "";
        $(function () {
            $.ajax({
                url:'FirstAjaxServlet?time='+new Date().getTime(),
                success:function (data) {
                    res = data;
                    $('#t_1').val(res);
                },
                async:false, //设置为异步请求
                cache:false, //禁用缓存
                error:function(err){
                    alert(err);
                }
            });

            $.ajax({
                url:'SecondAjaxServlet?time='+new Date().getTime(),
                success:function (data) {
                    $('#t_2').val(res+data);
                },
                cache:false,
                type:'get', //get方式请求
                error:function (err) {
                    alert(err);
                }

            })

        })
    </script>

</head>
    <body bgcolor="#87ceeb">
            <input id="t_1" type="text" value=""><br>
            <input id="t_2" type="text" value=""><br>
    </body>
</html>

2.7 jQuery AJAX主要参数data

data: Object或String类型参数发送给服务器的数据。将自动转换为请求字符串格式,GET请求中将附加到URL后,必须为Key/Value格式,如果为数组,jQuery将自动为不同值对应同一个名称

示例:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>jQuery实现Ajax请求处理</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        function validUserName() {
            var userName = $('#userName').val();
            $.ajax({
               url:'AjaxValidUserNameServlet',
               success:function (data,mess) {
                   console.log("执行success回调函数");
                   if (data ==='OK'){
                       $('#mess').text("系统提示,用户名可以使用");
                       $('#sub').attr('disabled',false);
                   } else {
                       $('#mess').text("系统提示,用户名已经被注册,请更换");
                   }


               },
                type:'post',
                cache:false,
                async:false,
                data:{name:userName},
                error:function (err) {
                    console.log("请求中出现错误回调此函数");
                }
            });
        }
    </script>

</head>
<body bgcolor="#87ceeb">

    <form action="">
        用户名称
        <input id="userName" type="text" onblur="validUserName()">
        <label id="mess"></label>
        <br>
        <input id="sub" type="submit" value="submit" disabled="disabled"> <br>
    </form>

</body>
</html>

2.8 jQuery AJAX主要参数dataType

2.8 jQuery AJAX主要参数dataType

示例:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>jQuery实现Ajax请求处理</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        function doAjax() {

            $.ajax({
                url:'AjaxReturnDataTypeServlet', //ajax请求服务器的url
                success:function (data,mess) { //如果请求成功,服务器成功返回,则执行此函数
                    //$('input').val(data); //处理返回文本
                    //$('body').append(data);
                    console.log("执行success回调函数");
                    data;
                },
                type:'post',
                cache:false,
                async:false,
                //dataType:'text', //设置期待返回普通的文本字符串
                //dataType:'html', //设置期待返回html标记代码
                dataType:'script',
                error:function (err) { //请求中出现错误回调此函数
                    console.log("请求中出现错误回调此函数");
                }
            });
        }
    </script>

</head>
<body bgcolor="#87ceeb">

    <input type="text" value="">
    <button onclick="doAjax()">Ajax请求返回数据类型</button>

</body>
</html>

2.9 jQuery AJAX主要参数error

2.9 jQuery AJAX主要参数error

2.10 jQuery AJAX主要参数success

2.10 jQuery AJAX主要参数success

2.11 jQuery AJAX主要参数timeout

timeout: 值类型参数,设置ajax请求的超时时间,单位为毫秒,如果在请求处理中超时,则抛出异常

2.12 jQuery AJAX中文处理

客户端使用contentType ajax函数设置请求内容编码格式

contentType:'application/x-www-form-urlencoded; charset=UTF-8', //设置请求编码格式

在提交到服务器后使用以下方式进行解码

resp.setContentType("text/html;charset=utf-8");

示例
客户端:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>jQuery实现Ajax请求处理</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script>
        function doAjax() {
            var name = $('input').val(); //获取用户名称

            $.ajax({
                url:'ChineseHandleServlet', //ajax请求服务器的url
                success:function (data,mess) { //如果请求成功,服务器成功返回,则执行此函数
                    console.log("执行success回调函数");
                    $('label').text(data);
                },
                type:'post',
                cache:false,
                async:true,
                dataType:'text', //设置期待返回普通的文本字符串
                contentType:'application/x-www-form-urlencoded; charset=UTF-8', //设置请求编码格式
                data:{username:name}, //传递请求参数
                error:function (err) { //请求中出现错误回调此函数
                    console.log("请求中出现错误回调此函数");
                }
            });
        }
    </script>

</head>
<body bgcolor="#87ceeb">

<input type="text" value="">
<button onclick="doAjax()">Ajax请求返回数据类型</button>
<label></label>

</body>
</html>

服务器端:

package com.xzit.servlet;

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

public class ChineseHandleServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("中文处理");
        resp.setContentType("text/html;charset=utf-8");
        String name = req.getParameter("username");
        System.out.println(name);
        PrintWriter out = resp.getWriter();
        out.write("hello, "+name);
        out.close();
    }
}

3.服务器端Java对象与JSON格式数据的转换

通常使用ajax实现java web的异步请求处理获得服务器返回的数据可以使用JSON格式进行封装,通常会使用成熟的java语言实现的服务器端组件来进行这种转化。

3.1 json-lib-x.x-jdkxx.jar 工具类

这个开源组件包主要实现对JSON格式数据与java对象的相互转换功能,首先需要部署一些包:


3.1 json-lib-x.x-jdkxx.jar 工具类包

这个开源组件包是主要实现对JSON格式数据与java对象的相互转化功能,可以利用内部组件以及相关方法实现对JSON进行操作。

JsonConfig提供辅助的JSON操作格式化功能,可根据用户要求对数据进行符合要求的格式转换。

将Java对象转换成JSON字符串以及JsonConfig进行格式化数据示例:

package com.xzit.servlet;

import com.xzit.database.DataBase;
import com.xzit.domain.Employee;
import com.xzit.domain.Student;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

public class UseJsonLibConvertJsonAndJavaObjectServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Employee emp = new Employee();
        emp.setBirth(new Date());
        emp.setEntryDate(new Date());
        emp.setId(UUID.randomUUID().toString());
        emp.setName("Lily");
        emp.setPhone("123456");
        emp.setSex("Female");

        JsonConfig jsCof = new JsonConfig();
        jsCof.registerJsonValueProcessor(Date.class,new JsonValueProcessor(){

            @Override
            public Object processArrayValue(Object o, JsonConfig jsonConfig) {
                System.out.println("转换数组中的日期对象");
                return new SimpleDateFormat("yyyy/MM/dd").format(o);
            }

            @Override
            public Object processObjectValue(String s, Object o, JsonConfig jsonConfig) {
                System.out.println("转日期对象");
                return new SimpleDateFormat("yyyy/MM/dd").format(o);
            }
        });

        String json = JSONObject.fromObject(emp, jsCof).toString();
        System.out.println("java对象转化为json格式的字符串:\n"+json);

        /*Student student = new Student();
        student.setName("Lily");
        List<Date> list = new ArrayList<>();
        list.add(new Date()); list.add(new Date()); list.add(new Date());
        student.setDateList(list);
        String json = JSONObject.fromObject(student, jsCof).toString();
        System.out.println("java对象转化为json格式的字符串:\n"+json);*/

        /*转换数组(集合)*/
        //String json = JSONArray.fromObject(DataBase.getEmpList(),jsCof).toString();
        //System.out.println(json);

    }
}

此组件包提供强大的功能,不仅可以转换java对象到JSON格式,也可以从JSON格式的字符串转化为Java对象

package com.xzit.servlet;

import com.xzit.domain.Employee;
import net.sf.json.JSONObject;

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


public class FromJsonToJavaObjectUseJsonLibServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String jsonStr = req.getParameter("emp");
        /*将客户端异步提交的json串简单转换成JSONObject*/
        JSONObject jsonObject = JSONObject.fromObject(jsonStr);
        System.out.println(jsonObject.get("id"));
        System.out.println(jsonObject.get("name"));
        System.out.println(jsonObject.get("birth"));

        /*进一步转换为期待的目标实体bean(Employee)*/
        Employee employee = (Employee) JSONObject.toBean(jsonObject, Employee.class);
        System.out.println(employee.getName()+ " "+ employee.getBirth().toString()+ " ");
        resp.getWriter().println("OK");
    }
}

3.2 gson-1.6.jar JSON转换工具

gson-1.6.jar是google提供的对JSON字符串与Java对象之间数据格式转换格式的库,使用此库中的相关方法能够简单实现java对象与JSON的转换

数据转换示例:

package com.xzit.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.xzit.domain.Employee;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.List;

public class UseGoogleGsonLibServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.setDateFormat("yyyy-MM-dd").create();

        /*Employee employee = new Employee();
        employee.setBirth(new Date());
        employee.setEntryDate(new Date());
        employee.setId("code1");
        employee.setName("Alisa");
        employee.setPhone("18999999");
        employee.setSex("female");

        System.out.println(gson.toJson(employee));*/

        /*从json字符串转化为java对象*/
        String jsonStr = req.getParameter("empList");
        /*从json数组转换为java对象*/
        //List<Employee> employeeList = gson.fromJson(jsonStr,new TypeToken<List<Employee>>(){}.getType());

       /* for (Employee employee:employeeList){
            System.out.println(employee.getName()+"\t"+employee.getBirth().toString());
        }*/

       /*转换一个非数组的json字符串到Emplpoyee对象*/
        Employee empObj = gson.fromJson(jsonStr,Employee.class);
        System.out.println(empObj.getName()+"\t"+empObj.getBirth().toString());

    }
}

4. jQuery如何处理JSON格式数据

方法1:

4.1 jQuery处理JSON格式的数据

方法2:

4.2 jQuery处理JSON数据

使用JSON提供的json2.js JavaScript库可以实现对象到JSON的转换和JSON到对象的转换

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <meta charset="UTF-8" content="text/html;charset=UTF-8">
    <title>jQuery 实现Ajax请求处理</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20160511/json2.min.js"></script>
    <script type="text/javascript">

    function Employee(id,name,birth,entryDate,sex,phone){
            this.id = id;
            this.name = name;
            this.birth = birth;
            this.entryDate = entryDate;
            this.sex = sex;
            this.phone = phone;
        }
        var emp; //Employee对象
        var emp2; //Employee对象
        var emp3; //Employee对象
        var jsonStr;
        var empList;
        function fromJsObjectToJSONString() {
            emp = new Employee('code1','alisa','1997-01-03','2020-07-21','female','123456');
            emp2 = new Employee('code2','alisa2','1997-01-03','2020-07-21','female','123456');
            emp3 = new Employee('code3','alisa3','1997-01-03','2020-07-21','female','123456');
            empList = [emp,emp2,emp3];

            jsonStr = JSON.stringify(emp);
            //alert(jsonStr);

            //jsonStr = JSON.stringify(empList);
            //alert(jsonStr);
        }

        function fromJSONStringToJsObject() {
            var tempEmp = JSON.parse(jsonStr);
            /*alert(tempEmp.id);
            alert(tempEmp.name);
            alert(tempEmp.birth);*/

            alert(tempEmp.length);
            alert(tempEmp[0].name);
            alert(tempEmp[1].name);
        }

    function ajaxRequest() {
        $.ajax({
            url:'UseGoogleGsonLibServlet',// ajax 请求服务器的url
            async:true,
            dateType:'text',
            type:'post',
            contentType:'application/x-www-form-urlencoded;charset=UTF-8',
            data:{empList:jsonStr},
            success:function(data,mess){// 如果请求成功,服务器成功返回,则执行此函数
                alert(data);
            },
            error:function(err){// 如果ajax请求中出现错误,则执行此回调函数
                alert(err+"出现错误,请稍后重试");
            }
        });
    }

    </script>
</head>
<body>

    <button onclick="fromJsObjectToJSONString()">从js对象转换为标准的JSON串</button><br>
    <button onclick="fromJSONStringToJsObject()">从标准的JSON串转换为js对象</button><br>
    <button onclick="ajaxRequest()">使用gson包工具</button>

</body>
</html>

5. jQuery.get(url, [data], [callback], [type])函数

5.1 jQuery.get()函数

6. jQuery.post(url, [data], [callback], [type])函数

6.1 jQuery.post()函数

代码示例:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <meta charset="UTF-8" content="text/html;charset=UTF-8">
    <title>jQuery 实现Ajax请求处理</title>
    <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/json2/20160511/json2.min.js"></script>
    <script type="text/javascript">

        function getFn() {
            var args = $('form').serialize(); //序列化表单对象
            $.get(
              'GetAndPostFunctionServlet?'+args,
                function (res) {
                    alert(res);
                },
                'text'
            );
        }

        function postFn() {
            var args = $('form').serialize(); //序列化表单对象
            $.post(
                'GetAndPostFunctionServlet?'+args,
                function (res) {
                    alert(res);
                },
                'text'
            );

        }

    </script>
</head>
<body>

    <form>
        姓名:<input name="name"><br>
        性别:<input name="sex" type="radio" value="M" checked="checked">男
        <input name="sex" type="radio" value="F">女<br>
        生日  <select name="birth">
            <option value="1997-10-20">1997-10-20
            <option value="1997-10-21">1997-10-21
            <option value="1997-10-22">1997-10-22
            <option value="1997-10-23">1997-10-23
        </select><br>
            入职日期<select name="entryDate">
            <option value="2015-10-20">2015-10-20
            <option value="2015-10-21">2015-10-21
            <option value="2015-10-22">2015-10-22
            <option value="2015-10-23">2015-10-23
        </select><br>
            电话<input name="phone"><br>
    </form>
    <button onclick="getFn()">序列表表单get</button>
    <button onclick="postFn()">序列表表单post</button>

</body>
</html>

7. serialize()函数

序列化函数,实现表单序列化


7.1 serialize()函数
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。