在jQuery UI Confirmation对话框之后调用Ajax

时间:2016-12-10 10:08:17

标签: javascript jquery html ajax jquery-ui

我正在开发一个模块供用户使用3个常规步骤验证他们的手机号码:

输入手机号码 - >接收引脚 - >输入PIN码进行验证

我的表单包含:

  • 2个文本框:
    • 手机号码(在页面加载时可见)
    • Pin(在AJAX响应后替换“Mobile#”)
  • 1“下一步”按钮

我的代码看起来像这样:

HTML

<form action="" method="post" enctype="multipart/form-data" id="form-product">
  <div id="dob_form">
    <label for="input-phone-number">Mobile Number</label>
    <input type="text" name="phone_number" value="" id="input-phone-number" />
  </div>
  <input type="button" value="Next" id="button-next" />
</form>

JS

(实际的代码包含额外的条件检查,这里没有用处,所以为了清楚起见我将其剥离了)

$('#button-next').bind('click', function() {

$.ajax({
    url: (api url),
    type: 'post',
    data: $('#dob_form :input'),
    dataType: 'json',
    cache: false,

    success: function(json) {

        if (json['phone-step'] == 1 && json['valid-number']) { //api returns that it's the phone number step and the number is valid

            $('#dob_form').html('' +
            '<label for="input-pin">Pin Code</label>' +
            '<input type="text" name="pin_code" value="" id="input-pin"  />');      

       } else if (json['pin-step'] == 1 && json['valid-pin']) { //api returns that it's the pin validation step and the pin is valid

          window.location.href = json['redirect'];

       } else { //show error }

   }
});

});

这一切都正常。

但是,我要添加的是一个模态确认对话框,只有在发送“PIN”AJAX电话之前才显示

换句话说,第一次单击“下一步”直接发送呼叫,但在第二步中,当用户输入引脚并单击“下一步”时,我想显示一个确认对话框。 如果他/她点击“确定”,将发送AJAX呼叫;在“取消”它只是关闭对话框,不会发送电话。

我设法使用 if语句 confirm()对话框;但是,我想使用 jQuery UI 添加自定义对话框。

我无法弄清楚如何做到这一点,因为我找不到从jQuery UI对话框获得响应的方法。

任何想法都表示赞赏。 感谢。

2 个答案:

答案 0 :(得分:1)

我设法制作了一个工作示例,并且沿途学习了一些jQuery UI!

我必须将事件处理程序和数据发送功能提取到单独的函数中以提高可读性。基本上,我会在每次点击#input-pin时检查HTML中是否存在#button-next,并使用它来确定是否已发送电话号码。如果没有,我会显示一个对话框。否则,我发送的数据可能是电话号码。

为了使下面的示例有效,我必须添加一个小复选框,允许您假装在发送电话号码后获得有效响应。您可以在HTML和JS中删除这些行,而不会破坏其余功能。

$('#button-next').bind('click', function() {
    if ($('#input-pin').length) {
        $('#confirm-send-pin').dialog({
            height: "auto",
            width: 500,
            modal: true,
            buttons: {
                'Send PIN': function () {
                    sendData()
                    $(this).dialog('close')
                },
                'Cancel': function () {
                    $(this).dialog('close')
                }
            }
        })
    } else sendData()
})

function sendData() {
    console.log('Data sent!')
    $.ajax({
        url: 'http://api.example.com/api-path',
        type: 'post',
        data: $('#dob_form :input'),
        dataType: 'json',
        cache: false,
        success: onDataReceived
    })
}
      
      
function onDataReceived (json) {
    if (json['phone-step'] == 1 && json['valid-number']) {
        $('#dob_form').html('' +
            '<label for="input-pin">Pin Code</label>' +
            '<input type="text" name="pin_code" value="" id="input-pin" />')
    } else if (json['pin-step'] == 1 && json['valid-pin']) {
        window.location.href = json['redirect'];
    } else {
        // error handling
    }
}

// This is just to make the example work

$('#test-dialog').on('change', function () {
    onDataReceived({ 'phone-step': 1, 'valid-number': 1 })
    this.disabled = true
})
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>


<form action="" method="post" enctype="multipart/form-data" id="form-product">
  <div id="dob_form">
    <label for="input-phone-number">Mobile Number</label>
    <input type="text" name="phone_number" value="" id="input-phone-number" />
  </div>
  <input type="button" value="Next" id="button-next" />
</form>
<div id="confirm-send-pin" title="Send PIN?" style="display:none">
  <p>Are you sure you want to send this PIN?</p>
</div>


<!-- Makes the example work -->
<label for="test-dialog">Pretend you sent a phone number</label>
<input type="checkbox" id="test-dialog" />

答案 1 :(得分:0)

您可以设置jQuery UI对话框以返回Deferred对象,该对象将告诉您是否选择了“确定”或“取消”操作:

function confirmDialog() {
    my def = $.Deferred();
    $('#myDiv').dialog({
       modal: true,
       buttons: [ {
           'ok': def.resolve,
           'cancel': def.reject
       } ]
    });
    return def.promise();
}

然后使用.then Promise链接将其合并为仅在confirmDialog被解析后才发送AJAX调用&#34;:

confirmDialog().then(sendAJAX);