A memorandum of processing that handles JSON Uses Struts 1.3.10.
Ajax with JS. Call Java.
main.js
$.ajax({
url : "./SearchBook.do",
type : "POST",
async : true,
data : "Data to throw to Java here",
dataType: "json",
success : function(result) {
//Processing on success
}
});
Put the result of various processing with the data received from JS into JSON type on Java side. String type and int type are prepared as data.
main.java
String title = "spark"
int totalPage = 152;
JSONObject result = new JSONObject();
result.put("title", title);
result.put("number of pages", totalPage);
The JSON type below is returned.
{"Title ":" Sparks "," Number of pages ":" 152 "}
$.ajax({
--abridgement--
success : function(result) {
//Processing on success
}
});
All you have to do is retrieve the target value with the key.
main.js
success : function(result) {
//Processing on success
$("#foo").text(result["title"]);
$("#bar").text(result["number of pages"]);
}
For the time being, this is done. If there is a better way, please teach me.
Change the key to alphabetic characters in Java.
main.java
String title = "spark"
int totalPage = 152;
JSONObject result = new JSONObject();
result.put("bookTitle", title);
result.put("totalPage", totalPage);
On the JS side, connect with. (Dot) and specify the key to get the value.
main.js
$.ajax({
url : "./SearchBook.do",
type : "POST",
async : true,
data : "Data to throw to Java here",
dataType: "json",
success : function(result) {
//Processing on success
$("#foo").text(result.bookTitle);
$("#bar").text(result.pager.totalPage);
}
dataType:" json "
and JSON type in dataType
of ajax, you did not need to parse.
Conversely, parse will result in an error.in short...
main.js
$.ajax({
url : "./SearchBook.do",
type : "POST",
async : true,
data : "Data to throw to Java here",
dataType: "json",
success : function(result) {
//Processing on success
$("#foo").text(result["title"]);
$("#bar").text(result["number of pages"]);
}
});
Or
main.js
$.ajax({
url : "./SearchBook.do",
type : "POST",
async : true,
data : "Data to throw to Java here",
success : function(result) {
//Processing on success
var data = JSON.parse(result);
$("#foo").text(result["title"]);
$("#bar").text(result["number of pages"]);
}
});
To be.
Recommended Posts