嵌套的ajax调用,第一个响应的回发

时间:2017-01-27 13:31:15

标签: jquery asp.net-ajax webmethod

我对嵌套的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调试它时它工作正常,而没有调试它jut运行服务器端方法而不在客户端捕获响应。

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

1 个答案:

答案 0 :(得分:1)

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

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