通过jquery从Web服务获取数据

时间:2010-10-30 13:04:05

标签: asp.net json jquery

这是我的网络服务:

public class Header : System.Web.Services.WebService {
    public Header () {}
    [WebMethod]
    public string GetArchive(string PageID)
    {
        StringBuilder sb = new StringBuilder();
        BusinessRules.News news = new BusinessRules.News();
        BusinessObject.NewsItemList newsList =
            news.GetListbySectionID(int.Parse(PageID));

        foreach (BusinessObject.NewsItem item in newsList)
        {
            sb.Append(item.ID + " : " + item.Date);
        }
        return sb.ToString();
    }

}

,其中

<body>
    <form id="form1" runat="server">
    <div>        
        <div runat="server" id="Content">
        </div>
        <div>
            <a id="LinkBtnAll" href="#">View</a>
        </div>
    </div>
    </form>
</body>

<script type="text/javascript">
    $(document).ready(function () {

        var ParamValue = $.getUrlVar("id");        

        $('#LinkBtnAll').click(function () {
            $.ajax({ type: "POST",
                url: "Services/Header.asmx/GetArchive",
                data: "{'PageID'," + ParamValue + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                cache: false,
                success: function (msg) {
                    $('#Content').text(msg.d);
                }
            })
            return false;
        });   
    });            
</script>

任何可以帮助我的人都行不通?

3 个答案:

答案 0 :(得分:1)

首先,对于Web方法应使用[ScriptMethod (ResponseFormat = ResponseFormat.Json)]属性,或者如果使用.NET 4.0,则在web.config中配置相同的属性。在这两种情况下,您都不需要手动阻止任何类型的JSON序列化。而不是你可以只返回对象本身。换句话说,你应该遵循 tvanfosson 的建议,但直接返回List<Article>

[System.Web.Script.Services.ScriptService]
public class Header : System.Web.Services.WebService {
    [WebMethod, ScriptMethod (ResponseFormat = ResponseFormat.Json)]
    public List<Article> GetArchive(int PageID)
    {
        BusinessRules.News news = new BusinessRules.News();
        BusinessObject.NewsItemList newsList = news.GetListbySectionID(PageID));
        return newsList.Select (a => new Article
                       {
                           ID = a.ID,
                           Date = a.Date
                       });
    }

    public class Article
    {
        public string ID { get; set; }
        public string Date { get; set; }
    }
}

我将输入参数PageID的类型从string更改为int,以显示输入参数不能只是字符串。它也可以是一个类实例(参见my old another)。

$(document).ready(function () {/*the code here you will see below*/});

内的客户端
var ParamValue = $.getUrlVar("id");
var pageID = parseInt(ParamValue,10);

$('#LinkBtnAll').click(function () {
    $.ajax({
        type: "POST",
        url: "Services/Header.asmx/GetArchive",
        data: {PageID: JSON.stringify(pageID)},
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $('#Content').text(msg.d);
        }
    })
    return false;
});

来自msg.d的结果的解码你应该以其他方式实现,因为msg.d是一个数组,但它是一个简单的JavaScript代码。

我建议您查看old answeranother one以获取更多信息。

答案 1 :(得分:0)

我为此目的编写了一个jquery插件。它使您的调用和参数传递变得更加容易。您可以从以下网址下载:http://www.4shared.com/file/Y72VBeLc/PageMethod.html

答案 2 :(得分:0)

你的JSON语法是错误的。整个事情需要用括号括起来,你的属性需要用逗号分隔,你应该引用你的属性名称和值,因为值可能有空格。

public class Header : System.Web.Services.WebService
{
    public Header () {}

    [WebMethod]
    public string GetArchive(string PageID)
    {
        StringBuilder sb = new StringBuilder("{");
        BusinessRules.News news = new BusinessRules.News();
        BusinessObject.NewsItemList newsList = news.GetListbySectionID(int.Parse(PageID));
        foreach (BusinessObject.NewsItem item in newsList)
        {
            sb.Append("\"" + item.ID + "\" : \"" + item.Date + "\"," );
        }
        return sb.ToString().TrimEnd(",") + "}";
    }
}

话虽如此,更好的方法是使用JSON序列化程序。请注意,以下示例中的格式与JSON对象的集合不同,而不是包含所有属性的单个JSON对象。您必须更改客户端代码才能解决此问题。

public class Header : System.Web.Services.WebService
{
    private class Article
    {
        public string ID { get; set; }
        public DateTime Date { get; set; }
    }

    public Header () {}

    [WebMethod]
    public string GetArchive(string PageID)
    {
        var articles = new List<Article>();
        BusinessRules.News news = new BusinessRules.News();
        BusinessObject.NewsItemList newsList = news.GetListbySectionID(int.Parse(PageID));
        var articles = newsList.Select( a => new Article
                       {
                           ID = a.ID,
                           Date = a.Date
                       };
        var stream = new MemoryStream();
        using (var serializer = new DataContractJsonSerializer(articles.GetType());
        serializer.WriteObject( stream, articles );
        return Encoding.Default.GetString( stream.ToArray() );
    }
}