开发者

Prevent redirection when form is submitted programmatically

I've got a form on the html page which gets submitted by javascript in some cases. The problem is that browser window change its location to the action URL specified for this form. Is there any way to pr开发者_如何学JAVAevent it of working this way?


Use a javascript library to submit the form via Ajax (xhr) or submit to iframe

Full Jquery example:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        $('#yourForm').submit(captureSubmit)
    })

    function captureSubmit(event) {
        var frm = $(event.originalTarget);
        $.ajax({
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: frm.serialize(),
            success: function(results) {
                // do stuff
                alert(results);
            },
            error: function(result) {
                // handle the error
                alert(result.status + ' ' + result.statusText);
            }
        });  
        return false;
    }
</script>

<form id="yourForm" action="foo.html" method="POST">
    Name: <input type="text" name="name">
    <button type="submit">Submit</button>
</form>

[EDIT] made example more complete.


Post it with Ajax


You can either:

  1. Submit with AJAX
  2. Submit to an iframe
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜