警报关闭后,表格输入为空

时间:2017-01-09 08:18:51

标签: javascript ajax alert confirm

<form id='formregister' autocomplete='off'>
    <input type='text' name='user' maxlength='50' placeholder='* Username'>
    <input type='text' name='pass' maxlength='50' placeholder='* Password'>
    <input type='text' name='name' maxlength='50' placeholder='Ime'>
    <button id='btnregister'>Register</button>
</form>

的javascript

$('#btnregister').click(function(){
$.ajax({
    url: 'regpro.php',
    type: 'post',
    data: $('#formregister').serialize(),
    success: function(data) {
        if (data == 'exists') {
            alert ('user already exists');  // after closing form is empty!
        }
        else if (data =='empty'){
            alert ('something is missing'); // after closing form is empty!
        }
        else{
            if (window.confirm('Registration is successfull. Do you wont to login?')){
                window.location.href = 'login.php';  // doesn't work
            }
            else {
                window.location.href = 'index.php';  // doesn't work
            }
        }
    }
});
});

那么为什么关闭警报后输入变为空,为什么重定向在确认对话框关闭后不起作用?

1 个答案:

答案 0 :(得分:2)

您应该在代码中添加event.preventDefault();

$('#btnregister').click(function(event){
    event.preventDefault();
    ...
});

当您单击按钮时,此方法将禁用表单的默认提交操作。