JavaWeb学习——Ajax

13 篇文章 3 订阅

目录

一、AJAX请求

二、javaScript 原生 Ajax 请求

三、jQuery 中的 Ajax 请求

1、四个ajax 方法

2、$.ajax 请求参数

3、$.get 请求和$.post请求

4、Jquery 的$.getJSON

5、一个表单序列化方法


一、AJAX请求

  • AJAX 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发 技术。
  • ajax 是一种浏览器通过 js 异步发起请求,局部更新页面的技术。
  • Ajax 请求的局部更新,浏览器地址栏不会发生变化 局部更新不会舍弃原来页面的内容

二、javaScript 原生 Ajax 请求

原生的 Ajax 请求:

  1. 我们首先要创建 XMLHttpRequest 对象
  2. 调用 open 方法设置请求参数
  3. 调用 send 方法发送请求
  4. 在 send 方法前绑定 onreadystatechange 事件,处理请求完成后的操作。

1)创建一个 html 页面,发起请求。代码:

<!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",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>

2)创建一个 AjaxServlet 程序接收

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")));
    }
}

3)在 web.xml 文件中的配

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

4)测试结果:

       通过上面的代码我们发现,编写原生的 JavaScript 我们自己要写很多的代码,而且还要考虑浏览器兼容问题。所以 “玩转”Java 系列 使用起来非常的不方便。那我们工作之后,怎么处理 Ajax 请求呢?

————我们一般会使用 JavaScript 的框架来解决这个问题,比如 Jquery 框架,它就有很好的 Ajax 解决方案 。


三、jQuery 中的 Ajax 请求

1、四个ajax 方法

  • $.ajax 方法
  • $.get 方法
  • $.post 方法
  • $.getJSON 方法

2、$.ajax 请求参数

data格式有两种:

  • name=value&name=value
  • {key:value}

常用的数据类型(dataType)有:

  • text 表示纯文本
  • xml 表示
  • xml 数据
  • json 表示 json 对象 
    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), "12321")));
    }
// ajax请求
$("#ajaxBtn").click(function(){
$.ajax({url:"http://localhost:8080/16_json_ajax_i18n_Web_exploded/ajaxServlet",
//data:"action=jqueryAjax",
data:{action:"jqueryAjax"},
type:"GET",
success:function (data) {
   //var jsonObj = JSON.parse(data);
   //$("#msg").html(jsonObj.id+"  :  "+jsonObj.name)
    $("#msg").html(" ajax 编号:" + data.id + " , 姓名:" + data.name);
},
  //dataType:"text"
  dataType : "json"
   });
});

3、$.get 请求和$.post请求

  • url:请求的 URL 地址
  • data:待发送 Key/value 参数。
  • callback:载入成功时回调函数。
  • type:返回内容格式,xml, html, script, json, text。
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), "12321")));
    }

    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), "12321")));
    }
// ajax--get请求
$("#getBtn").click(function(){				$.get("http://localhost:8080/16_json_ajax_i18n_Web_exploded/ajaxServlet",
"action=jqueryGet",function (data) {
$("#msg").html(" get 编号:" + data.id + " , 姓名:" + data.name);
},"json");
});
				
// ajax--post请求
$("#postBtn").click(function(){				$.post("http://localhost:8080/16_json_ajax_i18n_Web_exploded/ajaxServlet",
"action=jqueryPost",function (data) {
$("#msg").html(" post 编号:" + data.id + " , 姓名:" + data.name);
},"json");
});

4、Jquery 的$.getJSON

  • url:待载入页面的 URL 地址
  • data:待发送 Key/value 参数。
  • callback:载入成功时回调函数
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")));
    }
}
// ajax--getJson请求

$("#getJSONBtn").click(function(){	$.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet",
"action=jQueryGetJSON",function (data) {
	$("#msg").html(" getJSON 编号:" + data.id + " , 姓名:" + data.name);
		});
	});				

5、一个表单序列化方法

  • serialize()表单序列化方法
  • serialize() 方法可以把一个 form 表单中所有的表单项获取到,并以字符串 name=value&name=value 的形式进行拼接

    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 p = new Person(1,"柿子镭");
        Gson gson = new Gson();
        String personJsonString  = gson.toJson(p);
        response.getWriter().write(personJsonString);
    }
// serialize方法
$("#submit").click(function(){
// 把参数序列化
$.getJSON("http://localhost:8080/16_json_ajax_i18n_Web_exploded/ajaxServlet",
"action=jquerySerialize&" + $("#form01").serialize(),
function (data) {
     $("#msg").html(" Serialize 编号:" + data.id + " , 姓名:" + data.name);
	});
});
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值