1. 程式人生 > >後端開發基礎-Ajax學習-004——基於jQuery的Ajax使用

後端開發基礎-Ajax學習-004——基於jQuery的Ajax使用

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>