第六章 前端请求后端服务

以下主要使用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>

Title

$hello

loading...
这里我们通用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请求后端服务: Title

$hello

loading...

loading...
</body> </html>

results matching ""

    No results matching ""