[英]How to access model attribute in Javascript
I want to access a model attribute in Javascript. 我想在Javascript中访问模型属性。 I use the following code:
我使用以下代码:
model.addAttribute("data", responseDTO);
My DTO class: 我的DTO课程:
public class ResponseDTO {
private List<ObjectError> errors;
private Boolean actionPassed;
private String dataRequestName;
// and setter getter for all fields
}
I tried accessing the DTO using: 我尝试使用以下方式访问DTO:
var data = "${data}";
But it is giving me a string representation of responseDTO instead, ie com.req.dto.ResponseDTO@115f4ea
. 但是它给了我一个responseDTO的字符串表示,即
com.req.dto.ResponseDTO@115f4ea
。 I can successfully access a field inside the DTO using: 我可以使用以下方法成功访问DTO内的字段:
var data = "${data.actionPassed}";
But this is not working for the errors
attribute inside the DTO, as it is a List
of ObjectError
. 但这不适用于DTO中的
errors
属性,因为它是ObjectError
的List
。 How can I get complete responseDTO
object in Javascript? 如何在Javascript中获得完整的
responseDTO
对象?
Thanks! 谢谢!
EDIT : 编辑:
Initially I was using jquery.post
最初我使用的是
jquery.post
$.post('ajax/test.html', function(data) {
// Here I was able to retrieve every attribute even list of ObjectError.
});
Now I want to remove Ajax and want to convert it into non-ajax approach (because of some unavoidable reasons). 现在我想删除Ajax并希望将其转换为非ajax方法(因为一些不可避免的原因)。 So I am doing a normal form submit and want load same form again and trying to load
data
model attribute in Javascript so that I can keep the rest of the code as it is. 所以我正在做一个普通的表单提交,并希望再次加载相同的表单,并尝试在Javascript中加载
data
模型属性,以便我可以保持其余的代码。
I was wondering if it can be achieved in Javascript as it is doable using Jquery post? 我想知道它是否可以在Javascript中实现,因为它可以使用Jquery帖子?
EDIT 2 : 编辑2:
I tried (Thank you @Grant for suggestions) 我试过了(谢谢@Grant的建议)
JSONObject jsonObject =JSONObject.fromObject(responseDTO);
String jsonString = jsonObject.toString();
model.addAttribute("data",jsonString);
and in Javascript 并在Javascript中
var data = eval('('+ ${dataJson} +')'); // Getting error on this line
alert(data.actionPassed);
But getting error and no alert is displayed 但是会显示错误并且没有警报
Error : 错误:
First of all, there's no way to convert a Java object to a Javascript object directly since they have nothing to do with each other. 首先,没有办法将Java对象直接转换为Javascript对象,因为它们彼此无关。 One is server-side language and the other is client-side language.
一种是服务器端语言,另一种是客户端语言。
So to accomplish this goal, you have to do some convertion. 所以要实现这个目标,你必须做一些转换。 I think you have two options:
我想你有两个选择:
For option #1, you should use a library to generate JSON string by the Java object. 对于选项#1,您应该使用库来通过Java对象生成JSON字符串。 You can use this one JSON-lib .
你可以使用这个JSON-lib 。 eg:
例如:
JSONObject jsonObject = JSONObject.fromObject( responseDTO );
/*
jsonStr is something like below, "errors" represents the List<ObjectError>
I don't know what's in ObjectError, errorName is just an example property.
{
"dataRequestName":"request1",
"actionPassed":true,
"errors":[{"errorName":"error"},{"errorName":"unknown error"}]
}
*/
String jsonStr = jsonObject.toString();
model.addAttribute("dataJson", jsonStr);
/*In JSP, get the corresponding javascript object
by eval the json string directly.*/
<script>
var data = eval('('+'${dataJson}'+')');
</script>
For option #2, 对于选项#2,
//Pass java object as you do now
model.addAttribute("data",responseDTO);
//In JSP, include jstl taglib to help accessing List.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<script>
var errorArr = [], errorObj;
<c:forEach var="error" items="${data.errors}">
errorObj = { errorName: '${error.errorName}' };
errorArr.push(errorObj);
</c:forEach>
//Populate the corresponding javascript object.
var data = {
dataRequestName: '${data.dataRequestName}',
actionPassed: ${data.actionPassed},
errors: errorArr
};
</script>
As you can see, option #2 is complicated and only useful if the Java object is simple while option #1 is much easier and maintainable. 正如您所看到的,选项#2很复杂,只有在Java对象很简单而选项#1更容易和可维护时才有用。
So I just implemented a similar solution to Grant's first option with a List of objects, but used the Gson library to convert the object to a JSON string, then used JSON.parse() to turn it into a javascript object: 所以我刚刚用Grant的第一个选项和一个List对象实现了一个类似的解决方案,但是使用Gson库将对象转换为JSON字符串,然后使用JSON.parse()将其转换为javascript对象:
On the server: 在服务器上:
List<CustomObject> foo = database.getCustomObjects();
model.addAttribute("foo", new Gson().toJson(foo));
In the page javascript: 在页面javascript:
var customObjectList = JSON.parse('${foo}');
console.log(customObjectList);
Notice that when I reference the model object foo, that I do so as a string '${foo}'. 请注意,当我引用模型对象foo时,我将其作为字符串'$ {foo}'。 I believe you are getting your error because you reference it outside of a string.
我相信您收到错误是因为您在字符串之外引用它。 So the correct code would be:
所以正确的代码是:
var data = eval('('+ '${dataJson}' +')');
its very simple 它非常简单
in your spring controller
model.addAttribute("attributeName", "attributeValue");
in the script
<script type="text/javascript">
$(window).on('load', function () {
var springAttribute= '${attributeName}';
alert(springAttribute);
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.