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

发布表单后将json从服务器获取到jQuery中,jquery,json,post,Jquery,Json,Post,可能重复: 当我填写登录/注册表单时,服务器会将我发送到一个Json页面。 我尝试将json放入js/jquery文件中,而不重定向到该页面 有人能告诉我如何获取json数据吗 为了解释我的意思,我向您展示了一些代码+html页面 Html格式: <form id="registerForm" action="http://localhost:8081/rest/users/register" method="post" > <table> <tr>

可能重复:

当我填写登录/注册表单时,服务器会将我发送到一个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>
提交表单后得到的是一个新的HTML页面:

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

我如何将json输入到我的js文件中,而不必访问此html页面。

您可以将回调绑定到submit事件,而不是以常规方式提交表单。然后使用序列化表单数据,并通过ajax将其发送到服务器。有关更多详细信息,请参阅。大概是这样的:

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

    event.preventDefault();
});

您可以使用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
        }
    });
});

您可能想看看如何使用
.ajax()
。这似乎是正确的,但提交后,它总是重定向到该json/html页面。。这是为什么?我必须查看您的代码才能确定,
e.preventDefault()
应该可以阻止这种情况。(
$('#registerForm').bind('submit',function(e){e.preventDefault();$.ajax({'url':'http://localhost:8081/rest/users/register“,”type“:”POST“,”data“:$(this).serialize(),”complete“:函数(数据){alert(数据);},,”error“:函数(){alert(“errortje”);}});
)很抱歉视图不好。但是我找不到如何在这里添加代码块。我是stackoverflow的新手。摆脱()包装一切,我认为它应该可以工作。请参阅我的JSFIDLE:以获取示例。
$('#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
        }
    });
});