【问题标题】:How to run JavaScript code on Success of Form submit?如何在表单提交成功时运行 JavaScript 代码?
【发布时间】:2020-04-30 15:28:30
【问题描述】:

我有一个 Asp.Net MVC Web 应用程序。我想在表单提交时调用的 API 方法的成功响应上运行一些代码。

我有以下代码。

@using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { @class = "form-horizontal", id = "formID" }))
{

}

$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
    FunctionToBeCalled(); //JS function
}
}

但是FunctionToBeCalled()函数在APIMethod()之前被调用,但是我想在APIMethod()响应之后运行FunctionToBeCalled()函数。

所以我通过引用this 链接进行了以下更改。但是现在 APIMethod 被调用了两次。

$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
//Some custom javasctipt valiadations
    $.ajax({
        url: $('#formID').attr('action'),
        type: 'POST',
        data: $('#formID').serialize(),
        success: function () {
            console.log('form submitted.');
            FunctionToBeCalled(); //JS function
        }
    });

}
}
function FunctionToBeCalled(){alert('hello');}

所以我无法解决这个问题。

【问题讨论】:

  • 只需传递一个参数并使用条件语句来确定一个值是否可用。一旦可用,执行操作。 success: function(text){ if(text){ FunctionToBeCalled() } }
  • APIMethod 被调用两次而不是 JS 方法 FunctionToBeCalled()
  • 也添加 FunctionToBeCalled() 函数..
  • @MohammedShafeek 已更新
  • 添加返回false;在关闭之前 $('#formID').submit(function (e) { 将解决..

标签: javascript c# jquery ajax asp.net-mvc


【解决方案1】:

如果你想在表单提交的成功、失败等情况下执行一些工作,那么你需要在你的视图中使用Ajax调用。当你使用ASP.NET MVC时,你可以试试下面的方法。

查看:

$('form').submit(function (event) {
    event.preventDefault();

    var formdata = $('#demoForm').serialize();
    //If you are uploading files, then you need to use "FormData" instead of "serialize()" method. 
    //var formdata = new FormData($('#demoForm').get(0)); 

    $.ajax({
        type: "POST",
        url: "/DemoController/Save",
        cache: false,
        dataType: "json",
        data: formdata,

        /* If you are uploading files, then processData and contentType must be set to 
        false in order for FormData to work (otherwise comment out both of them) */
        processData: false, //For posting uploaded files
        contentType: false, //For posting uploaded files
        //

        //Callback Functions (for more information http://api.jquery.com/jquery.ajax/)
        beforeSend: function () {
            //e.g. show "Loading" indicator
        },
        error: function (response) {
            $("#error_message").html(data);
        }, 
        success: function (data, textStatus, XMLHttpRequest) {
            $('#result').html(data); //e.g. display message in a div
        }, 
        complete: function () {
            //e.g. hide "Loading" indicator
        },
    });
});

控制器:

public JsonResult Save(DemoViewModel model)
{
    //...code omitted for brevity
    return Json(new { success = true, data = model, message = "Data saved successfully." 
}

更新: 如果 SubmitButton 调用 JavaScript 方法或使用 AJAX 调用,则应在此方法中进行验证,而不是单击按钮,如下所示。否则,请求仍然发送到Controller 而不进行验证。

function save(event) { 
    //Validate the form before sending the request to the Controller
    if (!$("#formID").valid()) {
        return false;
    }
    ...
}

希望这会有所帮助。

【讨论】:

  • 我试过你的代码,它给出了同样的问题。 Save 被调用了两次。
  • 你能试试 tom 删除@using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { @class = "form-horizontal", id = "formID" })) {} 块吗?尝试使用普通的html form?
  • 以及如何调用javascript函数save?
  • 如果我从我的代码中删除html.beginform ......line。 $('form').submit( 将如何被调用
  • 您确定您在我的回答中尝试了完全相同的代码吗?因为我总是使用这种方法,它就像一种魅力。
【解决方案2】:

如下更新你的函数。

$('#formID').submit(function (e) {
    e.preventDefault();
    try{    
      $.validator.unobtrusive.parse("form");          
      if ($(this).valid()) {              
          $.ajax({
              url: $('#formID').attr('action'),
              type: 'POST',
              data: $('#formID').serialize(),
              success: function () {
                  console.log('form submitted.');
                  FunctionToBeCalled(); //JS function                      
              }
          });    
      }
    }
    catch(e){
      console.log(e);
    }                

});

检查浏览器控制台获取错误。以上代码将阻止提交表单。

我认为 $.validator.unobtrusive.parse("form") 行抛出错误。 为此,您需要添加以下 jQuery 库。

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script> 

【讨论】:

    【解决方案3】:

    如果您想使用 ajax 调用发布表单并将 post api URL 直接添加到 ajax 请求而不是使用 id 从您的 razor 表单标签中获取它,我认为您应该删除 razor 表单标签:

    这是您的代码的修订版本:

    <form method="post" id="formID">
        <!-- Your form fields here -->
        <button id="submit">Submit</button>
    </form>
    

    点击按钮提交表单:

    $('#submit').on('click', function (evt) {
            evt.preventDefault();
            $.ajax({
                url: "/Configuration/APIMethod",
                type: 'POST',
                dataType : 'json',
                data: $('#formID').serialize(),
                success: function () {
                   console.log('form submitted.');
                   FunctionToBeCalled(); //JS function
               }
           });
    });
    
    function FunctionToBeCalled(){alert('hello');}
    

    【讨论】:

      【解决方案4】:

      需要用到Ajax.BeginForm,这篇文章应该可以帮助到[https://www.c-sharpcorner.com/article/asp-net-mvc-5-ajax-beginform-ajaxoptions-onsuccess-onfailure/]

      【讨论】:

      【解决方案5】:

      这里的主要问题是我没有使用提交按钮,而是使用了链接并在 js 文件中处理了其余部分。这样,如果页面上没有js文件,就不会提交表单,并且有了这个js文件,它会自己发起表单提交,而不是点击提交按钮时提交表单

      您可以根据自己的解决方案调整它,看看它是如何响应的。我在生产中有这样的东西,它工作正常。

      (function() {
          $(function() {
              var _$pageSection = $('#ProccessProductId');
              var _$formname = _$pageSection.find('form[name=productForm]');
      
              _$formname.find('.buy-product').on('click', function(e) {
      
                e.preventDefault();
      
                if (!_$formname.valid()) {
                  return;
                }
                var formData = _$formname.serializeFormToObject();
      
                //set busy animation
      
                $.ajax({
                  url: 'https://..../', //_$formname.attr('action')
                  type: 'POST',
                  data: formData,
                  success: function(content) {
                    AnotherProcess(content.Id)
                  },
                  error: function(e) {
                    //notify user of error 
                  }
                }).always(function() {
                  // clear busy animation
                });
              });
      
      
              function AnotherProcess(id) {
      
                //Perform your operation
              }
            }
          }
      <div class="row" id="ProccessProductId">
      
        @using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { @class = "form-horizontal", name="productForm" id = "formID" })) {
        <li class="buy-product"><a href="#">Save & Proceed</a></li>
        }
      
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-26
        • 1970-01-01
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-09
        相关资源
        最近更新 更多