Announcement Announcement Module
Collapse
No announcement yet.
How to init a form by AJAX? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to init a form by AJAX?

    For example, I want to execute the "initRegister" method in Controller only after a user click the "Register" button in the page
    Code:
    @Controller
    public class UserController
    {
    
        @RequestMapping(method=RequestMethod.GET, value="/initPage.do")
        public String initPage(Model model)
        {
            return "home.jsp";
        }
    
        @RequestMapping(method=RequestMethod.GET, value="/initRegister.do")
        @ResponseBody
        public void initRegister(Model model)
        {
            model.addAttribute("reg", new RegisterForm());
        }
    }
    JQuery AJAX invoked by "Register" button: (show a small popup window for registration)
    Code:
    $.get('initRegister.do', function() //node: this is a callback function
                { 
                   $('body').append('<div>'
                       +'<form:form method="POST" modelAttribute="reg" '
                       + 'commandName="reg" action="register.do">'
                       + 'name: <form:input path="name"/>'
                       + '<input type="submit" value="Submit">'
                       + '</form:form>'
                       + '</div>');
                }
          );
    However I got the following error in the browser when I access "http://localhost:8080/.../initPage.do"
    Code:
    Neither BindingResult nor plain target object for bean name 'reg' available as request attribute
    The page works only if I move "model.addAttribute("reg", new RegisterForm());" to "initPage" method. But I don't need to create a RegisterForm instance until a uesr click "Register" button.

    How to solve it?
    Last edited by wlin; Sep 5th, 2012, 04:59 PM.

  • #2
    The key is, I want to use AJAX to init the Form instance then show popup, I don't want to init all forms along with page loading because the page has many different buttons, each of which uses different Form class.

    Comment

    Working...
    X