【问题标题】:ajax request firing twice on button clickajax 请求在按钮单击时触发两次
【发布时间】:2019-12-10 09:46:28
【问题描述】:

我正在使用淘汰赛和 .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然后它抛出错误Cannot read property 'value' of null

并且错误在线

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

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

的绑定有问题

有人知道怎么解决吗?

【问题讨论】:

  • 尝试将 validateAge 函数移到 calculateAge 函数之外。我相信它会立即被调用,然后在 $('body').onclick 函数上再次调用它
  • @Robert 如果我只是将函数 ValidateAge 移到 CalculateAge 之外,那么它会引发语法错误
  • 您还需要将您的 options_warningoptions_successoptions 变量声明移动到 validateAge 函数中。此外,您拥有的函数声明:function validateAge() { .... } 需要更改为 validateAge() { .... } 这应该可以解决您的语法错误。我会把它放在一个答案中,这样你就可以看到代码。希望能修复双 ajax 调用

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


【解决方案1】:

如 cmets 中所述,尝试将 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 函数时立即运行,以存储返回值。当您将点击侦听器添加到#MyButton 时,validateAge() 将被第二次调用

【讨论】:

  • validateAge函数里面没有alert选项,所以会失败
  • 它将在 validateAge 中的 swal(alert) 行失败
  • 我会将警报作为参数传递给 validateAge
  • 点击事件的正文在哪里?
猜你喜欢
  • 1970-01-01
  • 2021-06-27
  • 1970-01-01
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
相关资源
最近更新 更多