AJAX与java

原生 AJAX 请求的示例

折叠内容,点击展开

 

jQuery 实现方式

$.ajax方法

1.url  表示请求的地址
2.type  表示请求的方式 GET 或 POST 请求
3.type  表示发送给服务器的数据,
格式有两种
name=value&name=value
{key:value} success 请求成功,响应的回调函数
4.success(data, exStatus, jqXHR) 请求成功的回调函数
data  是返回的数据
exStatus  相应状态码
jqXHR 原生的 XmlHttpRequest 对象
5.error(XmlHttpRequest, exStatus, errorThrown)  请求失败的回调函数
errorThrown 可捕获的异常对象
6.contentType 请求数据类型
7.dataType  响应的数据类型
常用的数据类型有: text 表示纯文本,xml 表示 xml 数据,json 表示 json 对象

$.get 方法和$.post 方法
1.url  请求的 url 地址
2.data 发送的数据
3.callback  成功的回调函数
4.type  返回的数据类型

$.getJSON 方法
url 请求的 url 地址
data 发送给服务器的数据
callback  成功的回调函数

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: "http://localhost:8080/12_json_ajax_i18n/ajaxServlet",
            // data:"action=jQueryAjax",
            data: {action: "jQueryAjax"},
            type: "GET",
            success: function (data) {
              // alert("服务器返回的数据是:" + data);
              // var jsonObj = JSON.parse(data);
              $("#msg").html(" ajax 编号:" + data.id + " , 姓名:" + data.name);
            },
            dataType: "json"
          });
        });

        
        // ajax--get请求
        $("#getBtn").click(function () {
          $.get(
            "http://localhost:8080/12_json_ajax_i18n/ajaxServlet",
            "action=jQueryGet",
            function (data) {
              $("#msg").html(" get 编号:" + data.id + " , 姓名:" + data.name);
            },
            "json");
        });

        
        // ajax--post请求
        $("#postBtn").click(function () {
          $.post(
            "http://localhost:8080/12_json_ajax_i18n/ajaxServlet",
            "action=jQueryPost",
            function (data) {
              $("#msg").html(" post 编号:" + data.id + " , 姓名:" + data.name);
            },
            "json");
        });

        
        // ajax--getJson请求
        $("#getJSONBtn").click(function () {
          $.getJSON(
            "http://localhost:8080/12_json_ajax_i18n/ajaxServlet",
            "action=jQueryGetJson",
            function (data) {
              $("#msg").html(" getJSON 编号:" + data.id + " , 姓名:" + data.name);
            });

        });

        
        // ajax请求
        $("#submit").click(function () {
          // 把参数序列化
          $.getJSON(
            "http://localhost:8080/12_json_ajax_i18n/ajaxServlet",
            "action=jQuerySerialize&" + $("#form01").serialize(),
            function (data) {
              $("#msg").html(" Serialize 编号:" + data.id + " , 姓名:" + data.name);
            }
          );
        });

      });
    </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>
    <div id="msg">

    </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/>
    </form>
    <button id="submit">提交--serialize()</button>
  </body>
</html>

servlet

public class AjaxServlet extends BaseServlet {

    protected void javaScriptAjax(
        HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        System.out.println("Ajax请求过来了");

        Person person = new Person(1, "cess好帅");

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Gson gson = new Gson();
        String personJsonString = gson.toJson(person);

        response.getWriter().write(personJsonString);
    }

    protected void jQueryAjax(
        HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        System.out.println("jQueryAjax ---- 方法调用了");

        Person person = new Person(1, "cess好帅");

        Gson gson = new Gson();
        String personJsonString = gson.toJson(person);

        response.getWriter().write(personJsonString);
    }

    protected void jQueryGet(
        HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        System.out.println("jQueryGet ---- 方法调用了");

        Person person = new Person(1, "cess好帅");

        Gson gson = new Gson();
        String personJsonString = gson.toJson(person);

        response.getWriter().write(personJsonString);
    }

    protected void jQueryPost(
        HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        System.out.println("jQueryPost ---- 方法调用了");

        Person person = new Person(1, "cess好帅");

        Gson gson = new Gson();
        String personJsonString = gson.toJson(person);

        response.getWriter().write(personJsonString);
    }

    protected void jQueryGetJson(
        HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        System.out.println("jQueryGetJson ---- 方法调用了");

        Person person = new Person(1, "cess好帅");

        Gson gson = new Gson();
        String personJsonString = gson.toJson(person);

        response.getWriter().write(personJsonString);
    }

    protected void jQuerySerialize(
        HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException {
        System.out.println("jQuerySerialize ---- 方法调用了");

        System.out.println("用户名:" + request.getParameter("username"));
        System.out.println("密  码:" + request.getParameter("password"));

        Person person = new Person(1, "cess好帅");

        Gson gson = new Gson();
        String personJsonString = gson.toJson(person);

        response.getWriter().write(personJsonString);
    }
}

阅读剩余
THE END