【问题标题】:Posting to WebMethod with ajax error使用 ajax 错误发布到 WebMethod
【发布时间】:2017-07-03 19:11:49
【问题描述】:

第一步:

我已将我的脚本定义为: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 运行时错误:无法获取未定义的属性“d”或 空引用

【问题讨论】:

  • 如果你能包括哪个语句引发错误会更好
  • alert("这里" + data.d.toString());此行负责错误。
  • 你有什么&lt;head&gt;标签?您是否包含了适合您需要的 jQuery 库?

标签: c# asp.net ajax web-services webmethod


【解决方案1】:

您必须对数据进行字符串化:

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");
        }
    });
}

【讨论】:

  • 为什么会出现这个错误:JavaScript 运行时错误:无法获取未定义或空引用的属性“d”
  • 您使用的是哪个版本的 jQuery?你能显示完整的aspx页面吗?
【解决方案2】:

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

<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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-11
    • 2015-12-09
    • 2011-04-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-11
    • 2015-07-25
    • 1970-01-01
    相关资源
    最近更新 更多