【转】Spring Boot Ajax向后台传数据模板
js页面
$(document).ready(function () {
$("#search-form").submit(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
var search = {}
search["username"] = $("#username").val();
//search["email"] = $("#email").val();
$("#btn-search").prop("disabled", true);
$.ajax({
type: "POST",
contentType: "application/json",
url: "/api/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
var json = "<h4>Ajax Response</h4><pre>"
+ JSON.stringify(data, null, 4) + "</pre>";
$('#feedback').html(json);
console.log("SUCCESS : ", data);
$("#btn-search").prop("disabled", false);
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>"
+ e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR : ", e);
$("#btn-search").prop("disabled", false);
}
});
}
Controller类
@PostMapping("/api/search")
public ResponseEntity<?> getSearchResultViaAjax(@Valid @RequestBody SearchCriteria search, Errors errors) {
AjaxResponseBody result = new AjaxResponseBody();
//If error, just return a 400 bad request, along with the error message
if (errors.hasErrors()) {
result.setMsg(errors.getAllErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.joining(",")));
return ResponseEntity.badRequest().body(result);
}
List<User> users = userService.findByUserNameOrEmail(search.getUsername());
if (users.isEmpty()) {
result.setMsg("no user found!");
} else {
result.setMsg("success");
}
result.setResult(users);
return ResponseEntity.ok(result);
}
AjaxResponseBody类
@Data //import lombok.Data;
public class AjaxResponseBody {
String msg;
List<?> result;
}


