jQuery.post refreshes my page?

2019-05-23 21:31发布

I have the following code with a form on my page. But when I click submit, it seemed like my page refreshes.

form:

<form action='#' method='post'>
    <div><input type='text' name='name' /></div>
    <div><input type='submit' value='Save' /></div>
</form>

JS:

<script type='text/javascript'>
    $(document).ready(function() {
        $('form').bind('submit',function() {
            var str = $('form').serialize();

            $.post("save.php", { formString: str }, 
                function(data) {
                    alert("Saved: " + data);
                }
            );

        });
    });
</script>

Thanks a lot for any help!

1条回答
霸刀☆藐视天下
2楼-- · 2019-05-23 22:00

set a

return false;

to your form (for example on the onSubmit). Your form is sended by both jQuery ($.post) and the page itself, because you do not stop it to do that. Another option (works the same) is to let the jquery-part disable the default behaviour of your form:

//your code
$('form').bind('submit',function() {
   // more of your code
   return false;
}
查看更多
登录 后发表回答