I want to access a model attribute in Javascript. I use the following code:
model.addAttribute("data", responseDTO);
My DTO class:
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:
var data = "${data}";
But it is giving me a string representation of responseDTO instead, i.e com.req.dto.ResponseDTO@115f4ea
. I can successfully access a field inside the DTO using:
var data = "${data.actionPassed}";
But this is not working for the errors
attribute inside the DTO, as it is a List
of ObjectError
. How can I get complete responseDTO
object in Javascript?
Thanks!
EDIT :
Initially I was using 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). 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.
I was wondering if it can be achieved in Javascript as it is doable using Jquery post?
EDIT 2 :
I tried (Thank you @Grant for suggestions)
JSONObject jsonObject =JSONObject.fromObject(responseDTO);
String jsonString = jsonObject.toString();
model.addAttribute("data",jsonString);
and in Javascript
var data = eval('('+ ${dataJson} +')'); // Getting error on this line
alert(data.actionPassed);
But getting error and no alert is displayed
Error :
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…