jQuery中ajax请求的六种方法(三、二):$.get()方法

2.$.get()方法

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>jQuery中的ajax基础方法</title>
	</head>
	<script type="text/javascript" src="js/jquery-1.11.3.js"></script>
	<script type="text/javascript">
		$(document).ready(function() {
			$("#country").change(function() {
				// 拿到当前country中的值!
				var country = $(this).val();
				// 告诉服务器,我请求想要获得的数据格式是什么样的
				var myDataType = "json"; // xml / json
				// 如果country 取到了值,并且不为空的时候。
				if (country != undefined && country != null) {
					// 根据国家获取该国的城市列表,并设置到城市下拉框中
					/*
						在使用get方式的时候,发现其中的参数是四个[最开始使用基础$.ajax({})方法的是{},是一个对象]
						$.get(url, [data], [callback], [type])	
						
						这里的get四个参数:url、data、callback、type其中,url是必须的,其他用中括号括起来的,
						表示可以省略。
						
						注意:相比于ajax,get方式没有了ajax的{}表示对象!!!
						不然就直接报错了!这个是我遇到的jQuery能抛出的第一个错,很开心!
						Uncaught SyntaxError: Unexpected token +
					*/
					$.get(
						// url
						"cityServlet?dataType="+myDataType, // 需要访问的url
						// data
						{"country":country}, // 传递给后台的数据
						// 回调函数
						function(data) {
							// 在确定data为未定义,或者为空的时候,就不继续往下执行了。
							if (data == undefined || data == null) {
								// 不知道可不可以这样使用return。
								return;
							}
							// 这里使用的type并不是外部传入的,是我自定义的,告诉服务器我需要什么类型那里
							if ("json" == myDataType) {
								// 获取从服务器传过来的数据内容:其中的cities是服务器上规定的json的名字
								var cities = data.cities; // 直接的json对象
								// 清空原来的城市列表
								var $citySelect = $("#city"); // 约定jQuery的对象,命令都用$开头
							    $citySelect.empty();
								
								// 遍历cities,并且将其中的内容append到select中去
								$.each(cities, function(i, obj) {
									$citySelect.append("<option>"+obj.city+"</option>");
								});
							}
							if ("xml" == myDataType) {
								/*
								首先将data转成一个jQuery对象,因为xml不像json能够直接操作;
								必须先转化成jQuery对象,通过jQuery中提供的解析xml的方法进行操作!
								*/
								var $xmlDocument = $(data);
								var $cities = $xmlDocument.find("city");
								
								// 清空原来的城市列表
								var $citySelect = $("#city"); // 约定jQuery的对象,命令都用$开头
							    $citySelect.empty();
								
							 	// 遍历cities,并且将其中的内容append到select中去
								$.each($cities, function(i, obj) {
									/* 
									上面的json,直接通过data.cities,然后遍历cities的时候,通过foreach的obj
									直接obj.city就取出值了。
									但是xml的操作就相对麻烦了,xml要先转jQuery对象
									通过find查节点,然后组成一个数组,使用的时候,foreach出来,还需要把DOM转jQuery对象
									通过jQuery对象去取其中的text,层层剥离。
									可以看出在jQuery中,xml的处理方式和html的处理方式完全相同
									*/
									$citySelect.append("<option>"+$(obj).text()+"</option>");
								});
							}
						}, 
						// 返回值的类型,json? xml?
						myDataType
					);
				} else {
					// 未选择国家
					alert("请选择国家!");
				}
			});
		});
	</script>
	<body>
		<div style="width:100%;text-align: center;margin-top: 30px;">
	    	国家:<select id="country" style="width:160px;">
		    		<option>请选择</option>
		    		<option value="中国">中国</option>
		    		<option value="美国">美国</option>
	    		</select>
	    	&nbsp;&nbsp;---&nbsp;&nbsp;
	    	城市:<select id="city"></select>
    	</div>
	</body>
</html>

后台servlet:

package com.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/cityServlet")
public class CityServlet extends HttpServlet {

	private static final long serialVersionUID = -1046035703953361573L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String country = request.getParameter("country");
		String dataType = request.getParameter("dataType");
		/*
		String sendType = request.getParameter("sendType");
		if (!"post".equals(sendType)) { // 为get方式的时候,因为Tomcat7.0之前才有这个问题,忽略!
			country = new String(request.getParameter("country").getBytes("ISO-8859-1"), "utf-8");
		}
		*/
		StringBuffer sb = new StringBuffer("");
		if (!"xml".equals(dataType)) {
			sb.append("{");
			sb.append("\"cities\":[");
			if ("中国".equals(country)) {
				sb.append("{\"city\":\"北京\"},{\"city\":\"上海\"},{\"city\":\"广州\"},{\"city\":\"深圳\"}");
			} else if ("美国".equals(country)) {
				sb.append("{\"city\":\"华盛顿特区\"},{\"city\":\"纽约\"},{\"city\":\"洛杉矶\"},{\"city\":\"芝加哥\"}");
			}
			sb.append("]}");
			response.setContentType("text/html;charset=utf-8"); // 纯文本格式
		} else {
			sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><root>");
			if ("中国".equals(country)) {
				sb.append("<city>北京</city>").append("<city>上海</city>").append("<city>广州</city>").append("<city>深圳</city>");
			} else if ("美国".equals(country)) {
				sb.append("<city>华盛顿特区</city>").append("<city>纽约</city>").append("<city>洛杉矶</city>").append("<city>芝加哥</city>");
			}
			sb.append("</root>");
			response.setContentType("text/xml;charset=utf-8"); // xml格式
		}
		PrintWriter out = response.getWriter();
		out.println(sb.toString());
		out.flush();
		
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_36791569/article/details/81067608