简体   繁体   English

Ajax表单提交和Javascript确认错误

[英]Ajax Form Submission & Javascript Confirm Error

I have a form that submits through Ajax, which works perfectly at the moment. 我有一个通过Ajax提交的表单,目前工作正常。 I tried to add a confirm option to allow / prevent the Ajax submission through adding the following lines: 我尝试添加一个确认选项,通过添加以下行来允许/阻止Ajax提交:

    var answer = confirm('Submit now?');
    return answer // answer is a boolean

    if(answer) { ... }

Below is my full function, which, as you can see, fires on clicking the submit button. 下面是我的完整功能,如您所见,单击提交按钮时会触发。 The error occurs when the user selects okay in the dialog. 当用户在对话框中选择“正常”时,会发生错误。 The entire page is refreshed and any single Ajax warnings are returned at the top of a blank screen. 刷新整个页面,并在空白屏幕顶部返回任何单个Ajax警告。 In a normal case, without this confirm code, the error messages appear in the div#result tag at the bottom of the form. 在正常情况下,如果没有此确认代码,错误消息将显示在表单底部的div#results标记中。

$("#submitbtn").click(function() {

        var answer = confirm('Submit now?');
        return answer // answer is a boolean

        if(answer) { 

            $('#result').html('<img id="loading" src="images/loading.gif" />').fadeIn();
            var input_data = $('#create_po').serialize();
            $.ajax({
                type: "POST",
                url:  "<?php echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>",
                data: input_data,
                success: function(msg){
                    $('#loading').remove();
                    $('<div>').html(msg).appendTo('div#result').hide().fadeIn('slow');
                }
            });
            return false;

        }

    });

How should I implement a confirm dialog that doesn't refresh the screen? 我该如何实现不刷新屏幕的确认对话框? Any suggestions would be greatly appreciated. 任何建议将不胜感激。 Thanks! 谢谢!

You are doing return answer . 你正在return answer Which doesn't make any sense here. 这里没有任何意义。

It will stop the JavaScript function, and will return the boolean. 它将停止JavaScript函数,并返回布尔值。 Remove this line, and you're set 删除此行,然后设置

Also, add this to make your submit not fireing if the confirm box is false ;) 另外,如果确认框为false,则添加此项以使提交不会激活;)

if (answer){
    // your ajax call
}
else {
    return false;
}

Do not use this: 不要用这个:

<input type="submit">

Use this: 用这个:

<input type="button">

A submit button automatically submits a form. 提交按钮会自动提交表单。 A regular button does nothing. 常规按钮什么都不做。 You can use that to listen for clicks and THEN submit your form, or not. 您可以使用它来收听点击,然后提交您的表单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM