【问题标题】:AJAX - "Success" action is not invoked when specifying contentType and dataTypeAJAX - 指定 contentType 和 dataType 时不调用“成功”操作
【发布时间】:2016-02-08 16:26:36
【问题描述】:

我在执行 `AJAX 请求时遇到了一点问题。

当指定contentTypedataType 时,success 部分不会执行。 但是,当省略它时,它正在执行,但会显示生成的html 页面的全部内容。

这是我的 AJAX 调用:

$.ajax({
    type: "POST",
    url: "Default.aspx/GeneratePdfs",
    data: '{frequency: "' + $('#ddlFrequency option:selected').text() + '" }',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        $('#rptDisplay').text(data);
        alert("1");
    },
    failure: function () {
        //                $('#rptDisplay').text("Error");
        alert("2");
    }
});

这是code behind

[System.Web.Services.WebMethod]
public static void GeneratePdfs(string frequency)
{
    string test = frequency;
    HttpResponse response = HttpContext.Current.Response;
    response.Write(test);
}

这是html页面的片段:

<div id="rptDisplay" class="well" runat="server" clientidmode="Static">

</div>

我需要在我的div 部分显示从Web Method 返回的数据。

我做错了什么?

【问题讨论】:

    标签: asp.net ajax webmethod


    【解决方案1】:

    希望对您有所帮助:

    contentType :向服务器发送数据时。

    dataType:您期望从服务器返回的数据类型。如果没有指定,jQuery 将尝试根据响应的 MIME 类型推断它。

    请查找代码:

        [System.Web.Services.WebMethod]
        public static string GeneratePdfs(string frequency)
        {
            string test = "frequency";//Hard Code value
            HttpResponse response = HttpContext.Current.Response;
            return test;
        }
    
         Design:
          <asp:Content runat="server" ID="BodyContent"   ContentPlaceHolderID="MainContent">
          <div id="rptDisplay" class="well" runat="server" clientidmode="Static">
    
          </div>
        <script src="Scripts/jquery-1.7.1.min.js"></script>
        <script src="Scripts/jquery-ui-1.8.20.min.js"></script>
        <script type="text/javascript">
        $.ajax({
            type: "POST",
            url: "Default.aspx/GeneratePdfs",
            data: '{frequency: "' + $('#ddlFrequency option:selected').text() + '" }',
            contentType: "application/json;charset=utf-8",
           // dataType: "text/Json",
            success: function (data) {
                debugger;
                if (data.d!="") {
                    $('#rptDisplay').text(data.d);
                }
                alert("1");
            },
            failure: function () {
                //                $('#rptDisplay').text("Error");
                alert("2");
            }
        });
    </script>
    

    【讨论】:

    • 谢谢。现在它显示数据
    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2020-05-18
    • 2017-06-11
    相关资源
    最近更新 更多