[英]Send Java arraylist as JavaScript parameter
Problem问题
I send an array from StarConroller.java to Star.jsp page by model.addAttribute我将一个数组从StarConroller.java发送到Star.jsp页面model.addAttribute
StarConroller.java StarConroller.java
List<SBook> books = booksService.findAll();
model.addAttribute("books ", books);
I want to send this array of books to Star.js by clicking the "Show books" button in Star.jsp我想通过单击 Star.jsp 中的“显示书籍”按钮将这一系列书籍发送到 Star.js
Star.jsp Star.jsp
<button type="button" onclick="show(`${books}`)">Show books</button>
Star.js Star.js
function show(books) {
console.log(books);
}
When I click the "Show books" button I get the following in console当我单击“显示书籍”按钮时,我在控制台中得到以下信息
[SBook{SBookId=1, version=null, title='null', description='null'},
SBook{SBookId=2, version=null, title='null', description='null'},
SBookId{clauseId=3, version=null, title='null', description='null'}]
Issue问题
But I need a json array但我需要一个 json 阵列
update 1更新 1
SBook class SBook class
public class SBook{
private Integer sBookId;
private Integer version;
private String title;
private String description;
public SBook() {
}
public SBook(Integer sBookId, Integer version, String title, String description) {
this.sBookId= sBookId;
this.version = version;
this.title = title;
this.description = description;
}
//Getter & Setters
@Override
public String toString() {
return "SBook{" +
"sBookId=" + sBookId+
", version=" + version +
", title='" + title + '\'' +
", description='" + description + '\'' +
'}';
}
}
You are adding a list of objects to the HTTP response, the HTTP template engine will convert it to a string using the toString
method of SBook object.您正在向 HTTP 响应添加对象列表,HTTP 模板引擎将使用 SBook object 的
toString
方法将其转换为字符串。 The converted string is not a valid JSON.转换后的字符串不是有效的 JSON。
First, you need to convert list of objects to JSON format using parsing library (I'm using Jackson library in the below code):首先,您需要使用解析库将对象列表转换为 JSON 格式(我在以下代码中使用 Jackson 库):
List<SBook> books = booksService.findAll();
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(List.of(sBook));
model.addAttribute("books ", books);
Then you need to parse this JSON string back to javascript object using JSON.parse
:然后您需要使用 Z0ECD11C1D7A287401D148A23BBD7 将这个 JSON 字符串解析回 javascript
JSON.parse
。
function show(books) {
let parsed = JSON.parse(books);
console.log(parsed);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.