How to use jQuery to post JSON data to a Struts2 Action class

前端 未结 2 1581
臣服心动
臣服心动 2021-02-09 09:58

I\'ve a problem sending data from jQuery to struts2 action class. I have seen the question: JSON Jquery to Struts2 action but I don\'t understand the solution quite well.

<
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-09 10:26

    {"id":"1","code":"111","name":"ffffd"}
    

    Step 1 : Create a bean/pojo to accumulate/encapsulate the above fields

    class MyBean{
        String id,code,name;
        //getters & setters
    }
    

    Step 2 : Change your action code to receive a List of MyBeans

    public class Update extends ActionSupport{
        private List data;
    
       //other code, getters & setters
    }
    

    Step 3: Configure your action to de-serialize JSON data and fill the action fields (using json-plugin)

        
            
             
                true
            
    
    

    Step 4 : Make necessary changes in the ajax request body being sent to match the action-params/fields

    var data = JSON.stringify(dataObj);
    $.ajax({
      url: "Update",
      type: "post",
      data:  "data:"+data,
      dataType: 'json',
      contentType:"application/json;charset=utf-8",
      success : function(){
        alert("You made it!");
      }
    });
    

    The above code is untested.

提交回复
热议问题