# 第六章 前端請求后端服務
以下主要使用jQuery的ajax異步請求后端服務API。
### 引入jQuery
1. 展開項目工程目錄,在resources目錄下新建一個目錄,名稱為static.(SpringBoot框架會自動去查找static目錄)
2. 在static目錄下新建一個目錄,名稱為js
3. 在官網下載jquery文件:http://jquery.com/download/
4. 將下載好的jquery文件(jquery.min-xx.js)放到上面新建的js目錄里。本例子將下載的文件重命名為jquery.min.js
### 使用jQuery請求
一般后端服務提供兩種常用請求方法:GET和POST
**GET請求**
1、后端實現
展開src->main->java->lightsword->controller,這里我們繼續擴展MainController.java,增加一個新方法testGet,用于供前端頁面請求。
增加后MainController.java內容如下:
~~~
package lightsword.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class MainController {
@RequestMapping("/hello")
public ModelAndView hello(Model model){
ModelAndView modelAndView = new ModelAndView("index");
String hello = "Hello world";
model.addAttribute("hello", hello);
return modelAndView;
}
@RequestMapping(value = "/testGet", method = RequestMethod.GET)
@ResponseBody
public String testGet(){
return "this is a get request data";
}
}
~~~
以上提供了一個GET方法的API服務,調用地址為/testGet,返回數據為this is a get request data.
2、前端調用或請求
展開src->main->resources->templates,更改index.html,使用jquery請求testGet服務。
index.html內容如下:
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/js/jquery.min.js"></script>
</head>
<body>
<h3>$hello</h3>
<div id="container-get" style="border:1px solid red; width:300px; height:100px;">
loading...
</div>
</body>
</html>
<script type="text/javascript">
$(function(){
$.get('/testGet', function(data){
$("#container-get").html(data);
});
});
</script>
~~~
這里我們通用jQuery的$.get方法請求后端的服務。$.get方法具體使用可以自行百度。
打開瀏覽器訪問http://127.0.0.1:9527/hello
除了輸出Hello,也顯示后端返回的this is a get request data.
**POST請求**
在MainController.java里增加一個新方法testPost(在此方法中我們添加一個參數username),內容如下:
~~~
@RequestMapping(value = "/testPost", method = RequestMethod.POST)
@ResponseBody
public String testPost(@RequestParam String username){
String result = "hello " + username;
return result;
}
~~~
在index.html增加一個jQuery的post請求后端服務:
~~~
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/js/jquery.min.js"></script>
</head>
<body>
<h1>$hello</h1>
<div id="container-get" style="border:1px solid red; width:300px; height:100px;">
loading...
</div>
<div id="container-post" style="border:1px solid green; width:300px; height:100px;">
loading...
</div>
</body>
</html>
<script type="text/javascript">
$(function(){
$.get('/testGet', function(data){
$("#container-get").html(data);
});
var username = "lightsword";
$.post('/testPost', {username:username}, function(data){
$("#container-post").html(data);
});
});
</script>
~~~