Jquery的AJAX应用详解

案例一:取得服务端当前时间

  简单形式:jQuery对象.load(url),返回结果自动添加到jQuery对象代表的标签中间

<body>
当前时间:
<span id="time"></span><br />
<input type="button" value="获取时间" />
<script type="text/javascript">
    $(":button").click(function() {
      var url = "${pageContext.request.contextPath}/servlet/TimeServlet?time="+ new Date().getTime();
      $("#time").load(url);
    });
</script>
</body>
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(new Date());
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write(str);
pw.flush();
pw.close();
}

  复杂形式:jQuery对象.load(url,sendData,function(backData,textStatus,ajax){... ...})

<body>
当前时间:
<span id="time"></span><br />
<input type="button" value="获取时间" />
<script type="text/javascript">
$(":button").click(function() {
        //参数一:发送的路径
        var url = "${pageContext.request.contextPath}/servlet/TimeServlet?time="+ new Date().getTime();
//参数二:sendData发送请求体中的数据,以JSON文本书写的发送的参数
var sendDate = {
"name" : "哈哈",
"sal" : 6000
};
//参数三:回调函数,类似于传统方式ajax.onreadystatechange = 处理函数
$("#time").load(url,sendDate,function(backData,textStatus,xmlHttpRequest){
//回调函数中参数一:backData表示返回的数据,它是js对象
//回调函数中参数二:textStatus表示返回状态的文本描述,例如:success,error,
//回调函数中参数三:xmlHttpRequest表示ajax中的核心对象
alert("backData=" + backData);//输出:backData=2017-01-15 20:26:50
alert("textStatus=" + textStatus);//输出:textStatus=success
alert("xmlHttpRequest=" + xmlHttpRequest.readyState);//输出:xmlHttpRequest=4
alert("xmlHttpRequest=" + xmlHttpRequest.status);//输出:xmlHttpRequest=200
alert("xmlHttpRequest=" + xmlHttpRequest.responseText);//它是一个字符串,输出:xmlHttpRequest=2017-01-15 20:26:50
//项目中只需要使用backDate即可
});
    });
</script>
</body>
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
System.out.println("POST");
String name = request.getParameter("name");
String sal = request.getParameter("sal");
System.out.println(name+":"+sal);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf.format(new Date());
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write(str);
pw.flush();
pw.close();
}

  注意:对于load方法而言,如果请求体无参数发送的话,load方法采用GET方式提交,如果请求体有参数发送的话,load方法采用POST方式提交,使用load方法时,自动进行编码,无需手工编码

案例二:检查注册用户名和密码是否存在

<body>
<!-- 在异步提交的方式下,form标签的action和method属性没有意义-->
<form action="01_time.jsp" method="GET">
<table border="2" align="center">
<tr>
<th>用户名</th>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<th>密码</th>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="button" value="检查" style="width:111px" /></td>
</tr>
</table>
</form>
<span></span>
<script type="text/javascript">
$(":button").click(function() {
var username = $(":text").val();//哈哈
var password = $(":password").val();//123
var url = "${pageContext.request.contextPath}/servlet/UserServlet?time="+ new Date().getTime();
//手工写JSON文本
/* var sendData = {
"username" : username,
"password" : password
}; */
var sendData = $("form").serialize();//这行相当于上面三行
$.post(url,sendData,function(backDate) {
//backDate:
//如果服务器返回html,即backDate就是string,不要解析
//如果服务器返回json,即backDate就是object,要解析
//如果服务器返回xml,即backDate就是object,要解析
var $img = $("<img src='"+backDate+"' width='14px' height='14px'>");
$("span").text("");
$("span").append($img);
});
});
</script>
</body>

 

public class UserServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");//哈哈
String password = request.getParameter("password");//
String tip = "images/MsgSent.gif";
if("哈哈".equals(username) && "123".equals(password)){
tip = "images/MsgError.gif";
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter pw = response.getWriter();
pw.write(tip);
pw.flush();
pw.close();
}
}

  $.get(url,sendData,function(backData,textStatus,ajax){... ...})

  $.post(url,sendData,function(backData,textStatus,ajax){... ...})(提倡)

  注意:使用get或post方法时,自动进行编码,无需手工编码

  jQuery对象.serialize() :自动生成JSON格式的文本,要为每个jQuery对象设置一个name属性,因为name属性会被认为请求参数名,必须用<form>标签元素,如果属性过多,强烈推荐采用这个API 

案例三:jQuery解析XML

<?xml version="1.0" encoding="UTF-8"?>
<root>
<city>广州</city>
<city>深圳</city>
<city>香港</city>
<city>澳门</city>
<city>*</city>
<city>中山</city>
</root>
<body>
<input type="button" value="解析服务器响应的xml文件" />
<script type="text/javascript">
$(":button").click(function()
                {
  var url = "${pageContext.request.contextPath}/03_city.xml?time="+ new Date().getTime();
  var sendData = null;
  $.get(url, sendData, function(xml) {
  //用jquery中的api解析xml文件,这时的xml是js对象
  var $xml = $(xml).find("city");
  //迭代
  $xml.each(function() {
  var city = $(this).text();
  alert(city);
  });
  });
  });
</script>
</body>

 案例四:基于jQuery的AJAX二级联动

<body>
<select id="province">
<option>选择省份</option>
<option>江苏</option>
<option>浙江</option>
</select>
<select id="city">
<option>选择城市</option>
</select>
<!-- 省份->城市 -->
<script type="text/javascript">
//定位省份下拉框,同时添时内容改变事件
$("#province").change(
function() {
//清空原城市下拉框中的内容,除第一项外
$("#city option:gt(0)").remove();
//获取选中的省份
var province = $("#province option:selected").text();
//如果选中的不是"选择省份"
if ("选择省份" != province) {
$.ajax({
type : "POST",
url : "${pageContext.request.contextPath}/findCityByProvinceRequest?time="+ new Date().getTime(),
data : {
"province" : province
},
success : function(backDate,textStatus, ajax) {
//解析json文本
var array = backDate.setCity;
var size = array.length;
for (var i = 0; i < size; i++) {
var city = array[i];
var $option = $("<option>"+ city+ "</option>");
$("#city").append($option);
}
}
});
}
});
</script>
</body>
public class ProvinceCityAction extends ActionSupport{
private String province;
public void setProvince(String province) {
this.province = province;
}
public String findCityByProvince() throws Exception {
setCity = new LinkedHashSet<String>();
if("江苏".equals(province)){
setCity.add("南京");
setCity.add("扬州");
}else if("浙江".equals(province)){
setCity.add("杭州");
setCity.add("宁波");
setCity.add("温州");
}
return SUCCESS;
}
private Set<String> setCity;
public Set<String> getSetCity() {
return setCity;
}
}
上一篇:ZeroMQ接口函数之 :zmq_z85_decode – 从一个用Z85算法生成的文本中解析出二进制密码


下一篇:UVa 10814 - Simplifying Fractions