jQuery, JSON and ASP.NET PageMethods

本文关键字:NET PageMethods ASP and JSON jQuery | 更新日期: 2023-09-27 18:14:09

找到一篇很棒的文章,介绍如何使用jQuery来使用隐藏在代码后面的WebMethod。我想把它应用到我的网站上。但是我一直得到以下错误,尽管我确保参数名称是相同的。

        $(".StreamLike").live("mouseover", function () {
            var Id = $(this).parent().parent().find(".StreamIndex").html();
            alert(Id);
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/GetLikes',
                data: { "Id": Id },
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: LikesSuccess,
                error: LikesError
            });
        }); 
        function LikesSuccess(result, userContext, methodName) {
            for (var i in result) {
                alert(result[i]); 
            }

WebMethod:

[WebMethod]
public static string[] GetLikes(int Id)
{
    List<Like> Likes = Like.GetById(Id, false);
    string[] Senders = new string[Likes.Count];
    for (int i = 0; i < Likes.Count; i++)
    {
        Senders[i] = Likes[i].Sender;            
    }
    return Senders;
}

完整的错误信息如下:

{"Message":"Invalid JSON primitive: Id.","StackTrace":" at . .System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject () ' r ' n在System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal (Int32深度)' r ' nSystem.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(字符串输入,Int32深度限制,JavaScriptSerializer序列化器)'r'n atSystem.Web.Script.Serialization.JavaScriptSerializer.Deserialize (JavaScriptSerializer序列化器,字符串输入,类型类型,Int32深度限制)'r'n atSystem.Web.Script.Serialization.JavaScriptSerializer.Deserialize [T](字符串输入)' r ' nSystem.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest (HttpContextjavascript序列化器'r'n atSystem.Web.Script.Services.RestHandler.GetRawParams (WebServiceMethodData'r'n 'n atSystem.Web.Script.Services.RestHandler.ExecuteWebServiceCall (HttpContext背景下,WebServiceMethodDatamethodData)"、"ExceptionType":"系统。ArgumentException "}

总是点击LikesError…

jQuery, JSON and ASP.NET PageMethods

试试这个…

数据:JSON。stringify({"Id": Id})

该帖子正在将您的"Id"对象转换为名称/值对。例如Id = 12345。您必须首先对对象进行字符串化。

您可以使用chrome的开发工具查看响应值