发布表单后,从服务器获取json到jQuery

时间:2012-02-17 15:20:08

标签: jquery json post

  

可能重复:
  JQuery Ajax Return value

当我填写登录/注册表单时,服务器会将我发送到Json页面。 我尝试将json转换为js / jquery文件,而不重定向到该页面。

有人能告诉我如何获取json数据吗?

为了解释我的意思,我会向您展示一些代码+ html页面。

Html表格:

<form id="registerForm" action="http://localhost:8081/rest/users/register" method="post" >
<table>
    <tr>
        <td>
            <label for="firstname" class="normalFont"><span rel="localize[register.firstname]">First name</span></label>
        </td>
        <td>
            <input id="firstname" name="firstname" type="text" class="required">
        </td>
        <td class="status">

        </td>
    </tr>

    ... (some other fields)

    <tr>
        <td>
            <input type="submit" value="Register">
        </td>
    </tr>
</table>

服务器:

@Override
@RequestMapping(value="/register", method = RequestMethod.POST)
public @ResponseBody Message register(String firstname, String lastname, String username, String password, String email, String address, String zip, String city, String country) {

    try
    {
        User user = new User();

        user.setFirstname(firstname);
        user.setLastname(lastname);
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setAddress(address);
        user.setZip(zip);
        user.setCity(city);
        user.setCountry(country);

        userService.register(user);

        return new Message(true, "Registration Succesful");
    }
    catch (Exception ex)
    {
        return new Message(false, ex.getMessage());
    }
} 

提交表单后我得到的是一个新的HTML页面:

{"state":true,"content":"Registration Succesful"}

如何将json放入我的js文件中,而无需访问此html页面。

2 个答案:

答案 0 :(得分:5)

您可以使用jQuery来执行此操作。这样的事情。

$('#registerForm').bind('submit', function(e){
    e.preventDefault();
    $.ajax({
        'url': $(this).attr('action'),
        'type': 'POST',
        'data': $(this).serialize(),
        'complete': function(data){
            //data will contain the json coming back
        },
        'error': function(){
            //error occurred
        }
    });
});

答案 1 :(得分:0)

您可以将回调绑定到提交事件,而不是以正常方式提交表单。比使用.serialize序列化表单数据并通过ajax将其发送到您的服务器。有关详细信息,请参阅here。像这样:

$('#registerForm').on('submit' function(event) {
    $.post("url...", $("#registerForm").serialize(), function(result) {
        // Handle here...
    });

    event.preventDefault();
});
相关问题