【问题标题】:jQuery AJAX sequential calls with MVC使用 MVC 的 jQuery AJAX 顺序调用
【发布时间】:2017-02-16 15:34:50
【问题描述】:

我在一个 MVC 项目中有一个奇怪的设置,我有一个 @Ajax.BeginForm(),其中包含以下字段:-

  • 地址线1
  • 地址线2
  • 城镇
  • 邮政编码

我们需要用这个地址去谷歌地理编码,并通过点击 Ajax 表单上的提交按钮来获取纬度和经度。所以:-

@using (Ajax.BeginForm("EditLocation", "Location", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "new-locations", OnBegin = "return OnBegin()", OnSuccess = "OnSuccess()", InsertionMode = InsertionMode.InsertBefore }, new { @id = "EditLocationForm" })) {
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(false)
    <!-- Standard Text Fields -->
    @Html.TextBoxFor(m => m.Latitude)
    @Html.TextBoxFor(m => m.Longitude)
    <input type="submit" class="btn btn--gradient btn--right" id="EditLocationSubmit" />  
}

function OnBegin() {
    $.ajax({
        url: '/Location/CheckAddress/',
        datatype: "json",
        async: false,
        data: { addressLine1: $("#BrandLocationAddress_AddressLine1").val(), addressLine2: $("#BrandLocationAddress_AddressLine2").val(), town: $("#BrandLocationAddress_Town").val(), county: $("#BrandLocationAddress_County").val(), postcode: $("#BrandLocationAddress_Postcode").val(), },
        type: "POST",
        success: function (data) {
            if (data !== "NORESULTS") {
                $("#Latitude").val(data.Latitude);
                $("#Longitude").val(data.Longitude);
                return true;
            }
            else {

            }
        },
        error: function (response) {
            console.log(response);
            return false;
        }
    });
}

/Location/CheckAddress/ 的结果按预期返回纬度和经度,但 Ajax.BeginForm() 在填充两个 #Latitude 和 #Longitude 字段之前进入表单提交。当我查看模型的[HttpPost]时,纬度和经度都是0。

当我第二次发布时,这些字段是正确的纬度和经度值。我认为这可能是因为OnBegin() 允许Ajax.BeginFormsuccess 子句的最后一行执行之前完成它的工作,因此为0。

谁能建议在我知道success 子句的最后一行完成之前延迟提交第二个表单的方法?

【问题讨论】:

  • 删除async: false。这是非常糟糕的做法,因为它锁定了浏览器的 UI 线程。如果您检查控制台,浏览器甚至会警告您不要使用同步请求
  • 摆脱Ajax.BeginForm(),只使用$.ajax()(你已经在使用它了,为什么还要Ajax.BeginForm())。处理.submit()事件,让你ajax调用来获取坐标,并在它的成功回调中,让你ajax调用EditLocation()

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


【解决方案1】:

你需要从你的函数中返回false

var allowSubmit = false;
function OnBegin() {
    if (allowSubmit == true) { return true; }
    $.ajax({
        // ... code
        success: function (data) {
            // ... code
            // here you need to submit the form using 
            $( "#EditLocationForm" ).submit()
            allowSubmit = true;
        },
        error: function (response) {
          // .. code
        }
    });

    return false;
}

success,提交如上代码所示的表单。

另外,不要使用async: false 执行此操作:您不想在该操作进行时冻结 UI。您可能想要做的是禁用控件以便用户无法更改它们,然后在successerror 中重新启用它们。

【讨论】:

  • 嗨,我已经尝试过了,但它进入了一个不断循环调用初始 AJAX 调用的循环。这里有什么建议吗?我之前有这个设置,但在发生这种情况后放弃了它。
猜你喜欢
  • 2017-10-18
  • 2014-08-16
  • 1970-01-01
  • 2017-04-10
  • 2019-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多