jquery.ajax调用.aspx web方法

时间:2015-11-04 20:18:47

标签: jquery asp.net ajax webmethod

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

当web方法有一个婴儿车(如下所示)时,即使json数据中有多个数据点,它也能正常工作:

[System.Web.Services.WebMethod]
        public static string SendMyEmail(string EmailFromAddress)
        {

            return "good data from server: " + EmailFromAddress;

        }

1 个答案:

答案 0 :(得分:3)

你的ajax应该是这样的。删除&#39; =&#39;并替换为&#39;:&#39;在数据字段中创建适当的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);
    }
});