【问题标题】:Nested ajax call, postbacks on first response嵌套的ajax调用,第一次响应的回发
【发布时间】:2017-01-27 13:31:15
【问题描述】:

我在嵌套 AJAX 调用方面遇到了一个非常奇怪的问题。第一个回发的success 回发整个页面,因此第二个AJAX 调用success 不会触发。我碰巧对此感到非常困惑。以下是我正在尝试做的事情: 在按钮单击时调用 ajaxMethod():

Page1.aspx asp 按钮:

<asp:Button ID="btnGet" runat="server" Text="Get" OnClientClick="ajaxMethod();" />

JavaScript:

function ajaxMethod() {           
    var txtvalue = "123";

    $.ajax({
        type: "POST",
        url: "Page1.aspx/Method1",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: "{data:'" + txtvalue + "'}"
    }).done(function (response) {
        ajaxMethod2(response);
    });
}

function ajaxMethod2(response) {
    if (response.d == "success") {
        var ddlVacancyID = 12;

        $.ajax({
            type: "POST",
            url: "Page1.aspx/Method2",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{vacancyId:'" + ddlVacancyID + "'}"        
        }).done(function (response) {
            console.log('res2');
            ajaxMethod3(response);
        });
    } else {
        $("#<%=lblMsg.ClientID%>").text(response.d)
    }
}

function ajaxMethod3(response) {
    console.log('response received');
}

下面是我的 aspx.cs 代码:

[WebMethod]
public static string Method1(string data)
{
  return "success";
}

[WebMethod]
public static string Method2(int vacancyId)
{
  return "success";
}

一个更奇怪的问题是,当我通过 F11 调试它时它工作正常,而没有调试它只是运行服务器端方法而没有捕获客户端的响应。

请原谅我对语言的无知,因为我是它的新手。 另请注意,我已尝试使用 successcomplete,但没有运气。

【问题讨论】:

  • 如何调用ajaxMethod() 函数?如果您在提交form 元素时这样做,那么听起来您需要使用preventDefault()
  • @Rory McCrossan:我在按钮单击时调用 ajaxMethod()
  • 什么类型的按钮?您能否将该 HTML 添加到问题中
  • @Rory McCrossan:编辑我的问题..这是一个 asp 按钮。

标签: jquery asp.net-ajax webmethod


【解决方案1】:

在您的 asp 按钮中添加 return false 以禁用 ASP.NET PostBack:

<asp:Button ID="btnGet" runat="server" Text="Get" 
            OnClientClick="ajaxMethod();return false;" />

【讨论】:

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