ajax请求在按钮单击时触发两次

时间:2019-08-01 18:30:42

标签: javascript ajax asp.net-mvc knockout.js sweetalert2

我正在使用淘汰赛和.net,并且在html下方

<a href="javascript:void(0)" data-bind="click: CalculateAge">Calculate</a>

然后在我的打字稿模块中,我像下面这样调用函数CalculateAge

CalculateAge= (data: any, event: Event) => {
        $('body').on('click', '#MyButton', () => { validateAge(); });
        let inputHtml = "<input type = 'text' style= 'width: 300px' id = 'inputHtml' value = '" + receiverEmail + "'></input>";
        let myButton =
            "<button id='myButton'>Calc</button>";

        let alert: any = {
            title: 'Please calculate',
            html: "<table>" +
                "<tr>" +
                "<td><label>Age</label></td> " +
                "<td style= 'padding-right: 5px'>" + inputHtml + "</td><td>" + myButton + "</td>" +
                "</tr>" +
                "</table>",
            type: "warning",
            showCancelButton: true,
            showConfirmButton: false,
            cancelButtonText: "Cancel"

        };
        swal(alert);

        let options_warning: any = {
            title: 'Error',
            type: "warning",
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "ReEnter",
        };
        let options_success: any = {
            title: "Sent",
            type: "success",
            confirmButtonText: "Ok",
        }
        let options: any;

        function validateAge() {

            var age = (<HTMLInputElement>document.getElementById('inputHtml')).value;

            if (!age || age == "") {
                options_warning.title = "Age please fill";
                options = options_warning;
            }
            else {
                options = options_success;
            }

            swal(options).then(() => {
                if (options.type == "warning") {
                    swal(alert);
                }
                else {
                    $.post('MyApi/MyController/CalcualteAge',
                        { "Age": age }
                    );
                }
            });
        }           

    };

我单击href,这将打开甜蜜警报弹出窗口,然后输入年龄,然后单击名为 myButton 的按钮。这将检查年龄是否已满,然后进行ajax调用以计算年龄。我不在乎webapi是否失败。

当我单击 myButton 时,一切正常,并且仅使ajax调用一次。

但是当我单击href打开弹出窗口并单击 myButton 时,它将引发错误无法读取null的属性“值”

并且错误在线

var age = (<HTMLInputElement>document.getElementById('inputHtml')).value;

并且它使ajax调用两次。我认为 myButton

的绑定有问题

有人知道如何解决吗?

1 个答案:

答案 0 :(得分:0)

如评论中所述,尝试将validateAge()移动到CalculateAge()函数之外,如下所示:

CalculateAge = ( data: any, event: Event ) => {
    $( 'body' ).on( 'click', '#MyButton', () => { this.validateAge(); } );
    const inputHtml = '<input type = \'text\' style= \'width: 300px\' id = \'ReceiverEmailInput\' value = \'' + receiverEmail + '\'></input>';
    const myButton =
      '<button id=\'myButton\'>Calc</button>';

    const alert: any = {
      title: 'Please calculate',
      html: '<table>' +
        '<tr>' +
        '<td><label>Age</label></td> ' +
        '<td style= \'padding-right: 5px\'>' + inputHtml + '</td><td>' + myButton + '</td>' +
        '</tr>' +
        '</table>',
      type: 'warning',
      showCancelButton: true,
      showConfirmButton: false,
      cancelButtonText: 'Cancel'

    };
    swal( alert );

  }

  validateAge() {

    const options_warning: any = {
      title: 'Error',
      type: 'warning',
      confirmButtonColor: '#DD6B55',
      confirmButtonText: 'ReEnter',
    };
    const options_success: any = {
      title: 'Sent',
      type: 'success',
      confirmButtonText: 'Ok',
    };
    let options: any;

    var age = ( <HTMLInputElement>document.getElementById( 'inputHtml' ) ).value;

    if ( !age || age == '' ) {
      options_warning.title = 'Age please fill';
      options = options_warning;
    } else {
      options = options_success;
    }

    swal( options ).then( () => {
      if ( options.type == 'warning' ) {
        swal( alert );
      } else {
        $.post( 'MyApi/MyController/CalcualteAge',
          { 'Age': age }
        );
      }
    } );
  }

validateAge中包含CalculateAge函数时,该函数被视为Immediately Invoked Function Expression。将IIFE分配给变量后,在调用CalculateAge函数时该函数将立即运行,以存储返回值。当您将点击侦听器添加到validateAge()

时,第二次调用#MyButton
相关问题