接口使用Idea设计,返回json字符串。HTML5页面使用WebStorm设计,需要导入jquery。
设计接口需要有Gson包。
一、SpringBoot接口
@PostMapping("/getUserListJson")
public String getUserListJson() {
ListuserList = userRepository.getUserList();
NetResult> netResult = new NetResult<>(0, "getUserListJson success", userList);
String resultStr = new Gson().toJson(netResult);
return resultStr;
}二、HTML5页面代码
id:
查询
三、调用会发现不成功,因为接口没有允许跨域访问。在接口工程中添加一个类即可。
/**
* 设置文件
* 允许跨域访问
* 主要服务于前端对接口的调用
*/
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1
corsConfiguration.addAllowedHeader("*"); // 2
corsConfiguration.addAllowedMethod("*"); // 3
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}
运行结果: