jQuery对ajax的封装部分详解和案例
一:JQuery
Jquery:js的封装:
1:选择器:
2:API方法:
3:事件:
4:案例:【原有的js的案例,全部替换成jquery的形式】
5:对ajax的封装:
ajax:异步请求提交:
同步请求:
同步请求:客户端发出发出一个请求, 服务端, 接收请求, 在处理该请求时,
其他的请求只能进行等待, 当服务器端响应完毕, 整个页面全部刷新。
异步请求:
客户端可以同时发出多个请求, 多个请求, 都交给了xmh对象。引擎然后发送给服务器端
服务器端响应完毕, 会对页面进行局部刷新。
ajax 应用场景:
(1)用户名校验:
(2)百度的搜索框。
ajax 的开发步骤:
(1)获得ajax 对象:xmlHttpRequest : 不同的浏览器有差异.
(2)打开和服务端的链接:open(“GET”,“url”,true);
(3)发送数据:send(null);
(4)获得响应:
xhr.onreadystatechange= function(){
//获得服务端的响应数据:
xhr.responseText;
xhr.responseXML; xml数据:
//数据的响应状态:5个状态:
0:创建完毕
1:open()
2:send();
3:获得响应头:
4:响应完毕
xhr.readyState; //获得响应状态码:xhr.status; // 400 500 200
二:jquery 对ajax的封装:
$.ajax(); //ajax 复杂的形式, 能够处理get请求, 也能处理post请求。
语法:
$.ajax({//封装提交的参数:type:“POST|GET” , // type:请求方式url :“URL” , //ajax请求的地址:data:{ //请求参数(提交给后台的参数)// 将参数以?追加在url后边:" username=lisi&age=21 "username:“mrzhang”,age : 21,gender : “nan”}async: true, //默认为true, 异步请求。false:变成同步请求:cache: false, //默认为false, 页面不缓存结果dataType: "text", //服务端响应回来的数据类型:text:字符串文本:xml:xml文档:json 对象success: function(data,textStatus, xhr){// 服务端响应成功, 自动回调该函数://function当中含有三个参数,**三个参数都是可选择的。常用的就是第一个:data:返回来的数据:默认情况返回的数据类型:** String:text xml jsontextStatues:success error :xhr: 返回引擎对象, xmlHttpRequest;xhr.responseText;}})
说明:这些参数都是可选择的, 没有指定, 将会采用默认值:
常用的参数:type :url :data:datatype:success :
总结:get提交:提交参数:username=lisi&age=321
post请求:提交的参数:{ username:“lisi”, age:21 };
案例:检查用户名是否可用:
前端页面的准备:
用户名:, 用户名称是否可用的提示信息:
提交按钮:失去焦点事件:
下面代码中的lable是h5 新属性。
<html><head><title>My JSP 'regist.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript" src="js/jquery-1.8.3.js"></script></head><body><form action=""><label for="username">用户名:</label><input type="text" name="username" id="username"/> <span id="span1"></span><br/><input type="button" value="regist"/></form><script type="text/javascript">$(function(){//获得button按钮:var $btn = $(":button");$btn.click(function(){//获得input框:var $input = $("#username");//获得输入框当中的值:var username = $input.val();//发送ajax 请求:$.ajax({type: "GET",url : "${pageContext.request.contextPath}/servlet/RegistServlet",data: "username="+username,success : function(data,textStatus,xhr){//alert(data);//alert(xhr.responseText);以上方式和data 数据相同的:if(data==1){//说明用户可以被注册:$("#span1").html("<font color='green'>恭喜,用户名可以</font>");}else{//说明用户已经被注册过:$("#span1").html("<font color='red'>用户名称已经被注册</font>");}}})})});</script></body></html>
处理后端的servlet:
(1)获得前端的提交的用户名:
(2)调用service 层: 去数据当中进行查询: 返回一个结果:
(3)约定: 返回true, 用户名可用:
返回false,用户名称不可用:
package com.yidongxueyuan.web.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class RegistServlet2 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 {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");/** 1:获得参数:* 2: 判断用户存在:* 3:响应数据:*/String name = request.getParameter("username");String username = name.trim();/** name: 如果是admin: 不让其注册:* 不是admin, 可以注册:*/String tip = "images/MsgSent.gif";//正确:if("admin".equals(username)){tip="images/MsgError.gif";response.getWriter().println(tip);//响应回去的是一个图片的路径:}else{response.getWriter().println(tip);}}}
三: jquery封装了get提交:
$.get(url,[data],[ function(){}]);
案例:get方法发送时间到servlet:
<html><head><title>My JSP 'get.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript" src="js/jquery-1.8.3.js"></script></head><body><!-- 获得服务器的时间: --><input type="button" value="btn" id="btn"/><div></div><script>$(function(){$("#btn").click(function(){//发送请求: 没有参数:var url ="${pageContext.request.contextPath}/servlet/LoadTimeServlet";$.get(url,function(data){//获得时间// alert(data);//将值设置到div元素当中:$("div").html("<h1>"+data+"</h1>");});});});</script></body></html>
服务器端响应当前时间回去:
package com.yidongxueyuan.web.servlet;import java.io.IOException;import java.text.SimpleDateFormat;import java.util.Date;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoadTimeServlet extends HttpServlet {/** 获得当前服务器的时间, 让后响应给客户端浏览器:* (non-Javadoc)* @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date());response.getWriter().print(date);}}
四: jquery封装了post 提交:
$.post(url,[data], [function(){}]);
用法同上!
五: load方法: (推荐)
$("#links").load(url, [data], [function(){}]);
由jquery对象调用:
特点;
(1)既能处理get 请求, 又能处理post请求:
(2)当 load()没有参数提交, get 提交: 效率高:
当有参数提交的时候, post提交:
前端:
<html><head><title>My JSP 'load.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript" src="js/jquery-1.8.3.js"></script></head><body><!-- load没有提交参数, 默认使用的是get提交: --><script type="text/javascript">$(function(){$("#button").click(function(){var url="${pageContext.request.contextPath}/servlet/LoadServlet";$("#button").load(url);});});</script><script type="text/javascript">$(function(){$("#button2").click(function(){var url="${pageContext.request.contextPath}/servlet/LoadServlet";$("#button2").load(url,{username:"李四"});});});</script><input type="button" value="regist" id="button" /><input type="button" value="regist2" id="button2" /></body></html>
servlet:
package com.yidongxueyuan.web.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoadServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// doPost(request, response);System.out.println("get。。。。");}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");String name = request.getParameter("username");System.out.println(name);}}
