发布到 WebMethod 时出现 ajax 错误

Posting to WebMethod with ajax error

第一步:

我将我的脚本定义为:在 home.aspx 页面上:

function ShowCurrentTime() {
    var post = ({
        method: "POST",
        url: "home.aspx/GetData",
        dataType: 'json',
        data: { name: "Mobile" },
        headers: { "Content-Type": "application/json" },
        success: function (data) {
            alert("here" + data.d.toString());
            alert(data.d);
        },
        failure: function() {
            alert("Fail");
        }
    });
}

第二步:

从按钮调用脚本函数:它在 home.aspx 页面上:

<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />

第三步:

home.aspx.cs 页定义的 Web 方法:

[System.Web.Services.WebMethod]
public static string GetData(string name)
{
    return "Welcome";
}

我得到:

JavaScript runtime error: Unable to get property 'd' of undefined or null reference

试试这个,告诉我它是否有效:

<script type = "text/javascript">
                function ShowCurrentTime() {
                 var post = ({
                            method: "POST",
                            url: "home.aspx/GetData",
                            dataType: 'json',
                            data: { name: "Mobile" },
                            contentType: "application/json; charset=utf-8",
                      success: function (data) {
                          alert("here" + data.d.toString());
                              alert(data.d);},
                      failure: function() {
                          alert("Fail");}
                             });
                }
                </script>

您必须将数据字符串化:

data: JSON.stringify({ name: "Mobile" })

并像这样使用 ajax:

$.ajax({ ... });

已更新完整脚本:

function ShowCurrentTime() {
    $.ajax({
        method: "POST",
        url: "home.aspx/GetData",
        dataType: 'json',
        data: JSON.stringify({ name: "Mobile" }),
        contentType: "application/json",
        success: function (data) {
            alert("here" + data.d.toString());
            alert(data.d);
        },
        failure: function() {
            alert("Fail");
        }
    });
}