从Ajax命令获取WebMethod

时间:2014-10-22 01:56:37

标签: javascript c# jquery asp.net asp.net-ajax

如何从Ajax命令中获取WebMethod?

当我点击Button1时,我在Alert上得到错误代码:

"Error Code: [object Object]"

Default.aspx的:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
    function GetDateTime() {
        var jsonid = $("#<%= TextBox2.ClientID %>").val();
        var json1 = "{'id':'" + jsonid + "'}";
        $.ajax
        ({
            type: "POST",
            url: "Default.aspx/GetServerDateTime",
            data: json1,
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            success: function (result) {
                alert(result.d);
            },
            error: function (err) {
                alert("Error Code: " + err);
            }
        });
    }
</script>

Default.aspx.cs:

    protected void Button1_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scr", "Javascript:GetDateTime();", true);
    }
    [System.Web.Services.WebMethod]
    public static string GetServerDateTime(string id)
    {
        string datetimeid1 = "ID: " + id + " Date&Time" + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
        return datetimeid1;
    }

1 个答案:

答案 0 :(得分:0)

我认为由于JSON不当而导致您获得500 Internal Server Error。您可以使用JSON.stringify正确编码JSON,因此请更改:

var json1 = "{'id':'" + jsonid + "'}";

到此:

var json1 = JSON.stringify({ id: jsonid });