AJAX 不触发 WebMethod 但 returns 整个 HTML 页面成功

AJAX don't trigger WebMethod but returns whole HTML page on success

我在使 WebMethod 工作时遇到问题。都设置好了,我把它简化成最小的例子。

AJAX:

function DoAJAX() {
$.ajax({
    type: 'POST',
    url: 'faq.aspx/DoAJAX',
    data: "AJAX Test",
    dataType: 'text', 
    success: function (data, status) {
        debugger;
        alert(status + " " + data)
    },
    error: function () {
        alert("error!")
    }
 });
}

WebMethod(在faq.aspx.cs中,使用System.Web.Services ; 和 public 静态):

[WebMethod]
    public static string DoAJAX(string foo) {
        return foo;
    }
}

HTMLfaq.aspx,与 ScriptManager启用页面方法)

<%@ Page Title="" Language="C#" MasterPageFile="~/MP.Master" AutoEventWireup="true" CodeBehind="faq.aspx.cs" Inherits="Lottery.faq" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
    <input type="button" value="AJAX" onclick="DoAJAX()" />
</asp:Content>

点击后,AJAX调用return成功数据中包含以下内容:http://pastebin.com/X0Vke0qj

从未达到 DoAJAX() WebMethod 中的断点。

为什么不 return 发送的“AJAX Test”字符串,为什么 WebMethod 没有命中?

将类型更改为 json,添加内容类型并在数据中将 foo 参数作为 json 传递。

$.ajax({
    type: 'POST',
    url: 'faq.aspx/DoAJAX',
    data: "{ 'foo': 'AJAX Test' }",
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (data, status) {
        alert(status + " " + data.d)
    },
    error: function (xhr, status, error) {
        alert("error!")
    }
});

像这样更改您的代码:

.ASPX:

<head runat="server">
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $("#btnCallAjax").click(function () {
                DoAJAX();
            });

            function DoAJAX() {

                $.ajax({
                    type: "POST",
                    url: "faq.aspx/DoAJAX",
                    contentType: "application/json;charset=utf-8",
                    data: '{foo:"AJAX Test"}',
                    success: function (data, status) {
                        debugger;
                        alert(status + " " + data.d)
                    },
                    error: function () {
                        alert("error!")
                    }
                });
            }
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <input type="button" id="btnCallAjax" value="Call AJAX" />
    </form>
</body>

后面的代码:

public partial class faq : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static string DoAJAX(string foo)
    {
        return foo;
    }
}