jQuery中Ajax的使用方式
我们使用jQuery重写之前ajax案例来演示本案例:
演示案例
演示工程目录结构
需要引入 jquery-1.11.1.js脚本
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.study</groupId>
<artifactId>ajaxcase-day02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk15</classifier>
</dependency>
</dependencies>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>ajaxcase-day02</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>helloservlet</servlet-name>
<servlet-class>
com.servlet.HelloServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>helloservlet</servlet-name>
<url-pattern>/hello.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>checkservlet</servlet-name>
<servlet-class>
com.servlet.CheckServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>checkservlet</servlet-name>
<url-pattern>/check.do</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>loadcityservlet</servlet-name>
<servlet-class>
com.servlet.LoadCityServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loadcityservlet</servlet-name>
<url-pattern>/loadcities.do</url-pattern>
</servlet-mapping>
</web-app>
City.java
package com.entity;
import java.io.Serializable;
public class City implements Serializable{
private int id;
private String name;
//带参数构造器
public City(int id, String name) {
super();
this.id = id;
this.name = name;
}
// public int getNumber(){
// return 1000;
// }
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
HelloServlet.java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("进入HelloServlet...");
//响应输出一个text字符串信息
PrintWriter out = response.getWriter();
out.print("Hello Ajax");
out.close();
}
}
CheckServlet.java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CheckServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//获取请求参数name值
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
System.out.println("用户输入:"+name);
//模拟延迟
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//判断name值
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
if("scott".equals(name)){
out.print("用户名被占用");
}else{
out.print("用户名可用");
}
out.close();
}
}
LoadCityServlet.java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.entity.City;
import net.sf.json.JSONArray;
public class LoadCityServlet extends HttpServlet{
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("进入LoadCityServlet...");
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
//out.print("1:北京;2:上海;3:深圳");//【1】
//[{"id":1,"name":"北京"},{"id":2,"name":"上海"},{"id":3,"name":"天津"}]
// String data =
// "[{\"id\":1,\"name\":\"北京\"},"
// + "{\"id\":2,\"name\":\"上海\"},"
// + "{\"id\":3,\"name\":\"天津\"}]";//【2】
// System.err.println(data);
// out.print(data);
//获取数据
List<City> list = getCities();
//将数据转成JSON字符串
JSONArray jsonObj = JSONArray.fromObject(list);
System.out.println(jsonObj);//控制台显示
out.print(jsonObj.toString());//给Ajax对象返回.【3】
out.close();
}
private List<City> getCities() {
List<City> list = new ArrayList<City>();
City c1 = new City(1,"北京");
City c2 = new City(2,"上海");
City c3 = new City(3,"广州");
City c4 = new City(4,"深圳");
list.add(c1);
list.add(c2);
list.add(c3);
list.add(c4);
return list;
}
}
demo4.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery+Ajax</title>
<!-- 引入jQuery的js脚本 -->
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript">
//案例1:hello案例
//基于$.get实现
function sendRequest4(){
$.get( "hello.do",
function(data){
alert(data);
},
"text"
);
}
//基于$.ajax实现
function sendRequest1(){
$.ajax({
url:"hello.do",
type:"get",
dateType:"text",
success:function(data){
//data就是服务器返回的数据
alert(data+"11");
},
error:function(){
alert("程序发生错误");
}
});
}
</script>
<script type="text/javascript">
//案例2:用户名检测
//基于$.post实现
function sendRequest5(){
//获取请求参数
var name = $("#name").val();
//发送ajax请求
$.post("check.do",
{"name":name},
function(data){
$("#s2").html(data);
},
"text"
);
//提示正在检测
$("#s2").html("正在检测...");
}
//基于x.load实现
function sendRequest3(){
//获取请求参数
var name = $("#name").val();
//发送Ajax请求
$("#s2").load("check.do",{"name":name});
//提示正在检测
$("#s2").html("正在检测...");
}
//基于$.ajax实现
function sendRequest2(){
//获取请求参数、
var name = $("#name").val();
//发送Ajax请求
$.ajax({
url:"check.do",
type:"post",
data:{"name":name},
dataType:"text",
success:function(data){
//data是服务器返回的数据
$("#s2").html(data);
},
error:function(){
$("#s2").html("检测失败");
}
});
//提示正在检测
$("#s2").html("正在检测...");
}
</script>
</head>
<body>
<input type="button" id="btn1"
onclick="sendRequest1()" value="发送Ajax请求1">
<hr/>
用户名:<input type="text" id="name"
onblur="sendRequest3()">
<span id="s2"></span>
</body>
</html>
demo5.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>jQuery+JSON</title>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script type="text/javascript">
$(function(){
//等价于onload时机
$.ajax({
url:"loadcities.do",
type:"get",
dataType:"json",
success:function(data){
//data是服务器返回的信息,并且已经转成JSON类型了
alert(data)
for(var i=0;i<data.length;i++){
var id = data[i].id;//获取元素id值
var name = data[i].name;//获取元素name值
//创建一个option
var opt = "<option value='"+id+"'>"+name+"</option>"
//var opt = new Option(name,id);
//添加到select元素
$("#city").append(opt);
}
},
error:function(){
alert("加载失败");
}
});
});
</script>
</head>
<body>
<select id="city">
</select>
</body>
</html>
启动Tomcat 运行 ajaxcase-day02工程, 录入请求http://localhost:8088/ajaxcase-day02/demo4.html
启动Tomcat 运行 ajaxcase-day02工程, 录入请求http://localhost:8088/ajaxcase-day02/demo5.html