How to access model attribute in Javascript

前端 未结 3 2136
南笙
南笙 2020-12-17 11:00

I want to access a model attribute in Javascript. I use the following code:

model.addAttribute(\"data\", responseDTO);

My DTO class:

3条回答
  •  渐次进展
    2020-12-17 11:22

    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:

    On the server:

    List foo = database.getCustomObjects();
    model.addAttribute("foo", new Gson().toJson(foo));
    

    In the page 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}'. 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}' +')');
    

提交回复
热议问题