# Jquery與Ajax入門
[TOC]
## 導學
Jquery在此處不做講解,各位同學各自復習,主要需要學習的是通過Ajax實現前后臺的聯動。
## Ajax入門
Asynchronous JavaScript And XML (異步的JavaScript和XML),Ajax可以在不刷新頁面的前提下,進行頁面局部更新,Ajax不是新的技術,Ajax并不是W3C的標準。
在過去,我們在網頁中刷新頁面內容,需要重新從服務器獲取新的頁面。
Ajax的出現,揭開了無刷新更新頁面的新時代。
### Ajax優勢
* **優秀的用戶體驗**:Ajax最大的有點是能在不刷新整個頁面的前提下更新數據,這使得Web應用能迅速的回應用戶的操作。
* **提高Web程序的性能**:在傳統模式中,數據提交是通過表單來實現的,而數據的獲取則需要全頁面刷新來獲取整頁內容。Ajax可以不刷新整個頁面,按需提交數據給服務器,并接收服務器返回,然后通過dom操作,按需刷新頁面的一部分。
* **減輕服務器和帶寬的負擔**:Ajax的工作原理相當于在用戶和服務器之間加了一個中間層,使用戶操作與服務器響應異步化。把傳統方式下的一些服務器負擔的工作轉移到了客戶端。
### jquery中的ajax
$ajax()方法是jQuery最底層的Ajax實現。
結構:`$.ajax(options)`
options參數是一個對象:
| options參數名稱 | 說明 |
| --- | --- |
| url | 發送請求的地址 |
| type | 請求方式(`get|post`) |
| timeout | 請求超時時間(毫秒) |
| data | 發送到服務器的數據 |
| datatype | 預期服務器返回的數據類型(`text|json|xml|html|jsonp|script`) |
| success | 請求成功后調用的回調函數 |
| error| 請求失敗后調用的回調函數 |
~~~
public class News {
private String title;
private String date;
private String source;
private String content;
public News() {
}
public News(String title, String date, String source, String content) {
super();
this.title = title;
this.date = date;
this.source = source;
this.content = content;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
~~~
~~~
@WebServlet("/news_list")
public class NewsListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public NewsListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String type = request.getParameter("t");
List list = new ArrayList();
if(type != null && type.equals("pypl")) {
list.add(new News("PYPL:2018年5月份全球編程語言排行榜" , "2018-5-1" , "PYPL" , "..."));
list.add(new News("PYPL:2018年6月份全球編程語言排行榜" , "2018-6-1" , "PYPL" , "..."));
list.add(new News("PYPL:2018年7月份全球編程語言排行榜" , "2018-7-1" , "PYPL" , "..."));
list.add(new News("PYPL:2018年8月份全球編程語言排行榜" , "2018-8-1" , "PYPL" , "..."));
}else if(type == null || type.equals("tiobe")) {
list.add(new News("TIOBE:2018年5月份全球編程語言排行榜" , "2018-5-1" , "TIOBE" , "..."));
list.add(new News("TIOBE:2018年6月份全球編程語言排行榜" , "2018-6-1" , "TIOBE" , "..."));
list.add(new News("TIOBE:2018年7月份全球編程語言排行榜" , "2018-7-1" , "TIOBE" , "..."));
list.add(new News("TIOBE:2018年8月份全球編程語言排行榜" , "2018-8-1" , "TIOBE" , "..."));
}
String json = JSON.toJSONString(list);
System.out.println(json);
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println(json);
}
}
~~~
~~~
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(function(){
$.ajax({
"url" : "/ajax/news_list",
"type" : "get" ,
"data" : {"t":"pypl" , "abc":"123" , "uu":"777"},
//"data" : "t=pypl&abc=123&uu=777" ,
"dataType" : "json" ,
"success" : function(json){
console.log(json);
for(var i = 0 ; i < json.length ; i++){
$("#container").append("<h1>" + json[i].title + "</h1>");
}
},
"error" : function(xmlhttp , errorText){
console.log(xmlhttp);
console.log(errorText);
if(xmlhttp.status == "405"){
alert("無效的請求方式");
}else if(xmlhttp.status == "404"){
alert("未找到URL資源");
}else if(xmlhttp.status == "500"){
alert("服務器內部錯誤,請聯系管理員");
}else{
alert("產生異常,請聯系管理員");
}
}
})
})
</script>
</head>
<body>
<div id="container"></div>
</body>
</html>
~~~
## 案例:二級聯動菜單
~~~
public class Channel {
private String code;
private String name;
public Channel() {
}
public Channel(String code, String name) {
super();
this.code = code;
this.name = name;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
~~~
~~~
@WebServlet("/channel")
public class ChannelServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ChannelServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String level = request.getParameter("level");
String parent = request.getParameter("parent");
List chlist = new ArrayList();
if(level.equals("1")) {
chlist.add(new Channel("ai" , "前沿/區塊鏈/人工智能"));
chlist.add(new Channel("web" , "前端/小程序/JS"));
}else if(level.equals("2")) {
if(parent.equals("ai")) {
chlist.add(new Channel("micro" , "微服務"));
chlist.add(new Channel("blockchain" , "區塊鏈"));
chlist.add(new Channel("other" , "..."));
}else if(parent.equals("web")){
chlist.add(new Channel("html" , "HTML"));
chlist.add(new Channel("css" , "CSS"));
chlist.add(new Channel("other" , "..."));
}
}
String json = JSON.toJSONString(chlist);
response.setContentType("text/html;charset=utf-8");
response.getWriter().println(json);
}
}
~~~
~~~
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(function(){
$.ajax({
"url" : "/ajax/channel",
"data" : {"level" : "1"},
"type" : "get" ,
"dataType" : "json" ,
"success" : function(json){
console.log(json);
for(var i = 0 ; i < json.length ; i++){
var ch = json[i];
$("#lv1").append("<option value='" + ch.code + "'>" + ch.name + "</option>")
}
}
})
})
$(function(){
$("#lv1").on("change" , function(){
var parent = $(this).val();
console.log(parent);
$.ajax({
"url" : "/ajax/channel" ,
"data" : {"level" : "2" , "parent" : parent},
"dataType" : "json" ,
"type" : "get" ,
"success" : function(json){
console.log(json);
//移除所有lv2下的原始option選項
$("#lv2>option").remove();
for(var i = 0 ; i < json.length ; i++){
var ch = json[i];
$("#lv2").append("<option value='" + ch.code +"'>" + ch.name + "</option>")
}
}
})
})
})
</script>
</head>
<body>
<select id="lv1" style="width:200px;height:30px">
<option selected="selected">請選擇</option>
</select>
<select id="lv2" style="width:200px;height:30px"></select>
</body>
</html>
~~~