jquery.ajax 调用 .aspx 网络方法

jquery.ajax calling a .aspx web method

我在没有变量的 POC 中使用了以下代码,并且对所有内容进行了硬编码。在引入变量以准备使用此通道后,它停止了工作。可能存在我没有看到的语法错误,或者(我不敢说)这个 POC 无法支持此类请求?

来自我的 aspx 页面 sendEmail.aspx

     [System.Web.Services.WebMethod]
                public static string SendMyEmail(string EmailFromAddress, string EmailFromName, string EmailSubject, string EmailBody)
                {

                    return "data from server: " + Environment.NewLine +
                            "EmailFromAddress = " + EmailFromAddress + Environment.NewLine +
                            "from = " + EmailFromName + Environment.NewLine +
                            "from = " + EmailSubject + Environment.NewLine +
                            "from = " + EmailBody;

                }

    <script type = "text/javascript">
    function ShowCurrentTime() {
        alert("hi");

        $.ajax({
            type: "POST",
            url: "SendEmail.aspx/SendMyEmail",
            data: '{EmailFromAddress: "mike", EmailFromName="mike", EmailSubject="email subject here", EmailBody="email body here"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
    }

来自我的 html 网页:

<script type = "text/javascript">
function ShowCurrentTime() {
    alert("hi");

    $.ajax({
        type: "POST",
        url: "SendEmail.aspx/SendMyEmail",
        data: '{EmailFromAddress: "mike", EmailFromName="mike", EmailSubject="email subject here", EmailBody="email body here"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function (response) {
            alert(response.d);
        }
    });
}

function OnSuccess(response) {
    alert("all good");

    alert(response.d);
}
</script> 
</head>
<body style = "font-family:Arial; font-size:10pt">
<form id="form1" runat="server">
<div>
Your Name : 
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" 
    onclick = "ShowCurrentTime()" />
</div>
</form>
</body>
</html>

即使在 json 数据中有多个数据点:

,当 web 方法有一辆婴儿车(如下所示)时效果很好
[System.Web.Services.WebMethod]
        public static string SendMyEmail(string EmailFromAddress)
        {

            return "good data from server: " + EmailFromAddress;

        }

您的 ajax 应如下所示。删除“=”并替换为“:”以在数据字段中创建正确的 json。

$.ajax({
    type: "POST",
    url: "SendEmail.aspx/SendMyEmail",
    data: '{EmailFromAddress: "mike", EmailFromName: "mike", EmailSubject: "email subject here", EmailBody: "email body here"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: OnSuccess,
    failure: function (response) {
        alert(response.d);
    }
});