본문 바로가기
Developer/Javascript & jQuery

[Javascript] Java model.addAttribute를 Javascript로 불러오기

by 순수한소년 2016. 12. 1.
728x90
반응형

출처

http://stackoverflow.com/questions/9361977/how-to-access-model-attribute-in-javascript


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 :
enter image description here

shareimprove this question


728x90
반응형