javascript;Jquery;获取JSON对象,无刷新分页,异步加载,异步删除,实例。

AjaxNewsList:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <style type="text/css">
        .auto-style1 {
            width: 230px;
        }
        .auto-style2 {
            width: 300px;
        }
        .auto-style3 {
            width: 35px;
        }
        .auto-style6 {
            width: 80px;
        }
        .auto-style7 {
            width: 100px;
        }
    </style>
    <script type="text/javascript">
        window.onload = function () {
            initNews(1);
        };
        function initNews(pageindex) {
            var xhr = null;
            if (typeof (XMLHttpRequest) != undefined) {
                xhr = new XMLHttpRequest();
            }
            else {
                xhr = new ActiveXObject("Microsoft.XMLHttp");
            }
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    //把json字符串转换为json对象。(不安全,这里最好用json2.js或jquery)
                    //var newsList = eval("(" + xhr.responseText + ")");
                    var data = JSON.parse(xhr.responseText); //IE8之前需要引用json2.js
                    //设置分页超链接。
                    document.getElementById("div_PageNavigate").innerHTML = data.pageNavigate;
                    //注册a超链接onclick事件
                    var links = document.getElementById("div_PageNavigate").getElementsByTagName("a");
                    for (var a in links) {
                        links[a].onclick = function () {
                            window.location = '#p' + this.href.substr(this.href.lastIndexOf('/') + 1); //修改地址栏url,不重载页面。
                            initNews(this.href.substr(this.href.lastIndexOf('/')+1));  //取超链接‘/’后面的数字 仿博客园无刷新分页。
                            return false;
                        };
                    }

                    var newsList = data.dataList;
                    var tbody = document.getElementById("tbodyContent"); //获取tbody对象
                    //先清空tbody
                    tbody.innerHTML = "";
                    for (var i = 0; i < newsList.length; i++) {
                        var tr = document.createElement("tr"); //创建tr
                        //{"NewsId":25,
                        //"NewsTitle":"第一条国际新闻",
                        //"NewsContent":"新闻内容,新闻内容,新闻内容,新闻内容,新闻内容,新闻内容,新闻内容",
                        //"NewsIssueDate":"\/Date(1414078309687)\/",
                        //"NewsAuthor":"admin",
                        //"NewsImage":"Upload/BigPic/5/1/12/dcae98a1-a920-42b2-9e2d-c9896c8977dc_25.jpg",
                        //"NewsSmallImage":"Upload/SmallPic/5/1/12/dcae98a1-a920-42b2-9e2d-c9896c8977dc_small25.jpg",
                        //"NewsType":{"TypeId":2,
                        //"TypeName":"国际新闻"}
                        for (var name in newsList[i]) {
                            var td = document.createElement("td"); //创建td
                            var value = newsList[i][name];
                            if (name == "NewsId") { //Id
                                td.innerHTML = value;
                            }
                            else if (name == "NewsTitle") { //标题
                                td.innerHTML = value.length < 50 ? value : value.substring(0, 47) + "...";
                            }
                            else if (name == "NewsContent") {  //内容
                                td.innerHTML = value.length < 80 ? value : value.substring(0, 77) + "...";
                            }
                            else if (name == "NewsIssueDate") {  //日期
                                var da = eval('new ' + value.replace('/', '', 'g'));
                                td.innerHTML = da.toLocaleDateString();
                            }
                            else if (name == "NewsAuthor") {  //作者
                                td.innerHTML = value;
                            }
                            else if (name == "NewsSmallImage") {  //图片
                                td.innerHTML = "<img width=\"100\" height=\"100\" src=\"" + value + "\" />";
                            }
                            else if (name == "NewsType") {  //新闻类别
                                td.innerHTML = value.TypeName;
                            }
                            else {
                                continue;  //排除剩余的
                            }
                            tr.appendChild(td);  //附加到tr节点
                        }
                        //添加编辑和删除
                        var td = document.createElement("td");
                        td.innerHTML = "<a href=\"EditNews.aspx?id=" + newsList[i]["NewsId"] + "\">编辑</a>";
                        tr.appendChild(td);
                        var td = document.createElement("td");
                        td.innerHTML = "<a sid=" + newsList[i]["NewsId"] + " class=\"deleteClass\" href=\"javascript:void(0);\" >删除</a>";
                        tr.appendChild(td);
                        tbody.appendChild(tr); //附加到tbody节点
                    }
                    //绑定删除事件
                    initDeleteEvents(pageindex);
                }
            };
            xhr.open("Get", "GetNews.ashx?pageindex=" + pageindex, true);
            xhr.send(null);
        }
        //给删除超链接绑定onclick事件。
        function initDeleteEvents(pageindex) {
            var classNames = document.getElementsByClassName("deleteClass");
            for (var a in classNames) {
                classNames[a].onclick = function () {
                    if (window.confirm('真的要删除吗?')) {
                        //异步请求执行删除
                        var xhr = null;
                        if (typeof (XMLHttpRequest) != undefined) {
                            xhr = new XMLHttpRequest();
                        }
                        else {
                            xhr = new ActiveXObject("Microsoft.XMLHttp");
                        }
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState == 4 && xhr.status == 200) {
                                var _data = xhr.responseText;
                                if (_data == "1") {
                                    //重新异步加载数据
                                    initNews(pageindex);
                                    alert("删除成功!");
                                }
                            }
                        };
                        xhr.open("Get", "AjaxDeleteNews.ashx?id=" + this.getAttribute("sid"), true);
                        xhr.send(null);
                    }
                };
            }
        }
    </script>
</head>
<body>
    <!--#include file="Top.html"-->
    <div>
        <table border="1">
            <tr>
                <td class="auto-style3">Id</td>
                <td class="auto-style1">标题</td>
                <td class="auto-style2">内容</td>
                <td class="auto-style6">日期</td>
                <td class="auto-style6">作者</td>
                <td class="auto-style7">图片</td>
                <td class="auto-style6">新闻类别</td>
                <td>编辑</td>
                <td>删除</td>
            </tr>
            <tbody id="tbodyContent"></tbody>
        </table>
        <div id="div_PageNavigate"></div>
    </div>
</body>
</html>

 

GetNews.ashx:

<%@ WebHandler Language="C#" Class="GetNews" %>

using System;
using System.Web;
using System.Web.Script.Serialization;


public class GetNews : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        int pageindex = context.Request["pageindex"] == null ? 1 : int.Parse(context.Request["pageindex"]);
        int intPageSizes = 5;
        int recordCount;
        int pageCount;
        System.Collections.Generic.List<News.Model.Aspx_News> newsList = new News.BLL.Aspx_NewsBll().GetNewsListByPage(intPageSizes, pageindex, out recordCount, out pageCount);

        //生成分页超链接字符串。"GetNews.ashx?pageindex=" 
        string _pageNavigate = PageClass.strPage(recordCount, intPageSizes, pageCount, pageindex, "p/"); //主要用到p/截取字符串取后面数字。
        var data = new { pageNavigate = _pageNavigate, dataList = newsList };
        JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
        string json = jsSerializer.Serialize(data);
        context.Response.Write(json);
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

Jqurey版:

 

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="../Scripts/jquery-1.7.1.js"></script>
    <style type="text/css">
        .auto-style1 {
            width: 230px;
        }
        .auto-style2 {
            width: 300px;
        }
        .auto-style3 {
            width: 35px;
        }
        .auto-style6 {
            width: 80px;
        }
        .auto-style7 {
            width: 100px;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            initNews(1); 
        });
        function initNews(pageindex) {
            $.getJSON("GetNews.ashx", { "pageindex": pageindex }, function (_data) {
                //设置分页超链接。
                $("#div_PageNavigate").html(_data.pageNavigate);
                //注册a超链接onclick事件
                $("#div_PageNavigate a").click(function () {
                    window.location = '#p' + this.href.substr(this.href.lastIndexOf('/') + 1); //修改地址栏url,不重载页面。
                    initNews(this.href.substr(this.href.lastIndexOf('/') + 1));  //取超链接‘/’后面的数字 仿博客园无刷新分页。
                    return false;
                });
                var newsList = _data.dataList;

                $("#tbodyContent").empty(); //先清空tbody
                $.each(newsList, function (key, value) {
                    var id = value.NewsId;
                    var title = value.NewsTitle.length < 50 ? value.NewsTitle : value.NewsTitle.substring(0, 47) + "...";
                    var content = value.NewsTitle.length < 80 ? value.NewsTitle : value.NewsTitle.substring(0, 77) + "...";
                    var issueDate = eval('new ' + value.NewsIssueDate.replace('/', '', 'g')).toLocaleDateString();
                    var author = value.NewsAuthor;
                    var smallImage = "<img width=\"100\" height=\"100\" src=\"" + value.NewsSmallImage + "\" />";
                    var type = value.NewsType.TypeName;
                    var edit = "<a href=\"EditNews.aspx?id=" + id + "\">编辑</a>";
                    var del = "<a sid=" + id + " class=\"deleteClass\" href=\"javascript:void(0);\" >删除</a>";
                    //创建TR
                    var tr = $("<tr><td>" + id + "</td><td>" + title + "</td><td>" + content + "</td><td>" + issueDate + "</td><td>" + author + "</td><td>" + smallImage + "</td><td>" + type + "</td><td>" + edit + "</td><td>" + del + "</td></tr>");
                    $("#tbodyContent").append(tr);
                });
                //绑定删除事件
                initDeleteEvents(pageindex);
            });
        }
        //给删除超链接绑定onclick事件。
        function initDeleteEvents(pageindex) {
            $("a.deleteClass").click(function () {
                if (window.confirm('真的要删除吗?')) {
                    //异步请求执行删除
                    $.get("AjaxDeleteNews.ashx", { id: $(this).attr("sid") }, function (_data) {
                        if (_data == "1") {
                            //重新异步加载数据
                            initNews(pageindex);
                            alert("删除成功!");
                        }
                    });
                }
            });
        }
    </script>
</head>
<body>
    <!--#include file="Top.html"-->
    <div>
        <table border="1">
            <tr>
                <td class="auto-style3">Id</td>
                <td class="auto-style1">标题</td>
                <td class="auto-style2">内容</td>
                <td class="auto-style6">日期</td>
                <td class="auto-style6">作者</td>
                <td class="auto-style7">图片</td>
                <td class="auto-style6">新闻类别</td>
                <td>编辑</td>
                <td>删除</td>
            </tr>
            <tbody id="tbodyContent"></tbody>
        </table>
        <div id="div_PageNavigate"></div>
    </div>
</body>
</html>

 

posted @ 2014-10-28 07:10  hg一如既往  阅读(1652)  评论(0编辑  收藏  举报