jQueryUI .dialog(“close”)在ajax调用后无法正常工作

时间:2011-03-24 15:14:33

标签: jquery-ui jquery-ui-dialog

我正在使用jQueryUI的对话框和模态窗体选项来打开弹出窗体。当用户单击按钮时,它将其输入提交到数据库,然后应关闭对话框。除了关闭对话框外,一切正常。 (手动关闭按钮有效;它从PHP数据库脚本返回后不会自动关闭。这是脚本代码。(我试图加粗不起作用的行;显然你不能在代码标签内嵌套粗体,但该行被双星号包围,以使其脱颖而出。这些不是实际代码的一部分!)

<script>
    $(function() {
        // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
        $( "#dialog:ui-dialog" ).dialog( "destroy" );

        var name = $( "#name" ),
            email = $( "#email" ),
            company = $( "#company" ),
            plate = $( "#plate"),
            allFields = $( [] ).add( name ).add( email ).add( company ).add( plate ),
            tips = $( ".validateTips" );

        function updateTips( t ) {
            tips
                .text( t )
                .addClass( "ui-state-highlight" );
            setTimeout(function() {
                tips.removeClass( "ui-state-highlight", 1500 );
            }, 500 );
        }

        function checkLength( o, n, min, max ) {
            if ( o.val().length > max || o.val().length < min ) {
                o.addClass( "ui-state-error" );
                updateTips( "Length of " + n + " must be between " +
                    min + " and " + max + "." );
                return false;
            } else {
                return true;
            }
        }

        function checkRegexp( o, regexp, n ) {
            if ( !( regexp.test( o.val() ) ) ) {
                o.addClass( "ui-state-error" );
                updateTips( n );
                return false;
            } else {
                return true;
            }
        }

        $( "#dialog-form" ).dialog({
            autoOpen: false,
            height: 390,
            width: 350,
            position: 'top',
            modal: true,
            zIndex: 3000,
            buttons: {
                "Submit your plate": function() {
                    var bValid = true;
                    allFields.removeClass( "ui-state-error" );

                    bValid = bValid && checkLength( plate, "plate code", 1, 7 );
                    bValid = bValid && checkLength( email, "email", 6, 80 );
                    bValid = bValid && checkLength( company, "company", 1, 100);

                    bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ismi@instoremarketer.org" );


                    if ( bValid ) {

                            var nameStr = name.val();
                            var emailStr = email.val();
                            var companyStr = company.val();
                            var plateStr = plate.val();

                            var string = 'name='+ nameStr+'&email='+emailStr+'&company='+companyStr+'&plate='+plateStr;
                            //alert('string: '+string);


                            $.ajax({
                               type: "POST",
                               url: "submit_plate.php",
                               data: string,
                               dataType: 'json',
                               cache: false,
                               success: function(returnData){
                                                            alert(returnData.msg);
                                if(returnData.error === false) {
                                    **$( this ).dialog( "close" );**
                                }
                                else {
                                    alert("Error: "+returnData.msg);
                                }
                              }

                             });


                    }
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
            },
            close: function() {
                allFields.val( "" ).removeClass( "ui-state-error" );
            }
        });

        $( "#submit-plate" )
            //.button()
            .click(function() {
                $( "#dialog-form" ).dialog( "open" );
            });
    });
</script>

有什么想法吗? 已编辑添加PHP代码

<?php
include('../cfg/ez_sql.php');
include('../cfg/db_setup.php');

$err = false;
if (isset($_REQUEST['plate'])) {

    $raw = "INSERT INTO dot_plate_submissions (plate_code, plate_name, plate_company, plate_email) VALUES ('%s', '%s', '%s', '%s')";
    $clean = sprintf($raw,
               mysql_real_escape_string($_REQUEST['plate']),
               mysql_real_escape_string($_REQUEST['name']),
               mysql_real_escape_string($_REQUEST['company']),
               mysql_real_escape_string($_REQUEST['email']));

    //error_log("cleaned query: $clean");

   $db->query($clean);
}
else {
    $err = true;
}

if($err) {
    $return['error'] = true;
    $return['msg'] = "There was an error submitting your plate";
}
else {
    $return['error'] = false;
    $return['msg'] = "made it to php";
}
echo json_encode($return);
?>

因此,即使错误为false,ajax调用仍应返回两个数据。

5 个答案:

答案 0 :(得分:26)

更改$ .ajax调用以包含上下文,以便$(this)在回调中有效:

$.ajax({
    type: "POST",
    url: "submit_plate.php",
    data: string,
    dataType: 'json',
    context: $(this),
    cache: false,
    success: function(returnData){
        if(returnData.error === false) {
            $( this ).dialog( "close" );
            } else {
                  alert("Error: "+returnData.msg);
            }
    }   
});

答案 1 :(得分:10)

初始化对话框时,请执行以下操作:

var dialog = $( "#dialog-form" ).dialog({....});

准备好关闭对话框后,请尝试:

,而不是使用$(this)
$(dialog).dialog("close");

我过去必须在我写过的解决方案中做到这一点,我遇到了同样的问题

答案 2 :(得分:0)

在“错误”子功能中而不是“成功”写:

$("#diaolog-form-id").dialog("close");

答案 3 :(得分:0)

我使用了Anthony Shaw的解决方案。它对我很有用,而且我使用的是ASP.net AJAX,所以看起来这个问题与PHP无关。

这是一些简单的JavaScript来完成这项工作:

var DialogOps = function () {        
    var _dialog;
    this.showDialog = function () {
        _dialog = $('#dialog').dialog({
          // dialog options here
        });
    }
    this.closeDialog = function () {
        $(_dialog).dialog('close');
    }
}
var dialogOps = new DialogOps(); 

致电dialogOps.showDialog()打开对话框,然后dialogOps.closeDialog()关闭对话框。

答案 4 :(得分:-4)

几个月前我解决了这个问题,但忘了回到这里并发布解决方案。它与我的代码无关;这只是jqueryui和jquery之间的版本冲突。我使用的是旧版本的jquery;一旦我将我的库更新为jqueryui所需的版本(实际上在演示页面上非常清楚地注明了这一点;我不能仔细阅读!)这一切都正常工作。