I handed over JSON when I made a simple TODO application, so a memorandum I am using Ajax communication with jQuery
todo.js
/**Add new to database. */
function postItem(newContent) {
let todo = {
content: newContent
};
$.ajax({
type: "post",
url: contextPath + "/post", //OK if it is the URL to call Controller
data: { jsonTodo: JSON.stringify(todo) }, //JSON(Associative array)To a string
dataType: "json"
}).then(function (result) {
console.log('You can write the processing at the time of success. As below.');
let content = result.content;
}, function () {
console.log('You can write the processing at the time of failure');
});
Kimo is JSON.stringify (converts the target JSON to a string)
TodoController.java
/**
*Add a new TODO.
* @param todo New post TODO
* @TODO with return update reflected
*/
@ResponseBody //Since the annotation has a built-in JSON encoder, you can return the object directly to JS.
@PostMapping("/post")
public Todo post(@RequestBody Todo todo) throws JsonParseException, JsonMappingException, IOException {
todoRepository.saveAndFlush(todo); //db update
return todo;
}
TodoController.java
@ResponseBody //Automatically converts the returned object to a string that can be interpreted in JSON
@GetMapping("/find_all_asc")
public List<Todo> findAllOrderASC(){
List<Todo> todos = todoRepository.findAll(new Sort(Direction.ASC, "id"));
return todos;
}
todo.js
/**TODO list initialization*/
$.getJSON(contextPath + "/find_all_asc", null,
function (data, textStatus, jqXHR) { //JSON is stuck in data
//You can describe the process you want to do with the acquired JSON
data.forEach(todo => {
console.log(todo.content);
});
}
);
JavaScript
$(function () {
/**
* layout.Context path obtained from html.
*Example)/elabel/If you want to access edit, click "contextPath"+ 'elabel/edit'Can be used as a URL.
*/
contextPath = $('#contextPath').val();
});
/**If you want to change the setting, please describe it in the individual Ajax method. */
(function () {
$.ajaxSetup({
cache: false,
/**Do not cache the response of Ajax communication used once. */
timeout: 15000,
/**Timeout setting (provisional)*/
beforeSend: function (xhr, settings) {
/**Processing just before the start of communication*/
setCsrfTokenToAjaxHeader();
// showKurukuru();
},
success: function (data, status, xhr) {
/**Processing when communication is successful*/
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
/**Processing when communication fails*/
console.log("ajax communication failed");
console.log("XMLHttpRequest : " + XMLHttpRequest.status);
console.log("textStatus : " + textStatus);
console.log("errorThrown : " + errorThrown.message);
},
complete: function (xhr, status) {
/**Processing when communication is completed (regardless of whether it is an error or not)*/
//hideKurukuru();
},
});
})();
/**
*Function that can embed tokens by CSRF measures of Spring Security in header of ajax communication.
*Please use it by calling it just before the Ajax communication to be used..
*/
function setCsrfTokenToAjaxHeader() {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$(document).ajaxSend(function (e, xhr, options) {
xhr.setRequestHeader(header, token);
});
}
Thymeleaf
<meta name="_csrf" th:content="${_csrf.token}" />
<meta name="_csrf_header" th:content="${_csrf.headerName}" />
<input id="contextPath" type="hidden" th:value="${#request.getContextPath()}" />
Nifty JSON.stringify (http://www.symmetric.co.jp/blog/archives/1568) Reference article to POST from ajax to java POST from ajax to java (http://brissyu.blogspot.jp/2015/09/11spring-boot-web-ajax-csrf.html) Receive json by POST in spring3 (http://ponkotsusechan.hatenadiary.jp/entry/2016/02/01/173000_1)
Recommended Posts