jQuery.post refreshes my page?

谁都会走 提交于 2019-12-22 13:06:16

问题


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:


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;
}


来源:https://stackoverflow.com/questions/7524971/jquery-post-refreshes-my-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!