How to access model attribute in Javascript

前端 未结 3 2036
南笙
南笙 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<CustomObject> 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}' +')');
    
    0 讨论(0)
  • 2020-12-17 11:25

    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>
    
    0 讨论(0)
  • 2020-12-17 11:33

    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. 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:

    1. Convert ResponseDTO object to JSON string and pass it to jsp and you may get the javascript object directly.
    2. Pass ResponseDTO object to JSP and populate the javascript object as what you are trying now.

    For option #1, you should use a library to generate JSON string by the Java object. You can use this one JSON-lib. e.g:

    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,

    //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.

    0 讨论(0)
提交回复
热议问题