程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> Ajax讀取txt並對txt內容進行分頁顯示,ajax分頁顯示

Ajax讀取txt並對txt內容進行分頁顯示,ajax分頁顯示

編輯:關於.NET

Ajax讀取txt並對txt內容進行分頁顯示,ajax分頁顯示


  1 function TransferString(content)
  2     {
  3         var string = content;
  4         try{
  5             string=string.replace(/\r\n/g,"<BR>")
  6             string=string.replace(/\n/g,"<BR>");
  7             string=string.replace(/[ ]/g,"&nbsp;")
  8             string=string.replace(/\ +/g,"&nbsp;")
  9         }catch(e) {
 10             alert(e.message);
 11         }
 12         return string;
 13     }
 14 
 15     var pageIndex = 1;
 16     var id = $("#aId").val();
 17     var url = $('#urlArticleContent').val();
 18     var txt = '';
 19     var pageSize = @(ConfigurationManager.AppSettings["ArticlepageSize"]);
 20     var page=5;
 21     var pageCount = 0;
 22     $(function() {
 23         if(url!="")
 24         {
 25             txt = ($.ajax({ url: url, async: false })).responseText;
 26             if (txt.indexOf('http://www.w3.org/1999/xhtml')==-1) {
 27                 pageCount = Math.ceil(txt.length / pageSize);
 28                 $("#PageCount").html(pageCount);
 29                 $('#word').html(TransferString(txt.substring(0, pageSize)));
 30                 $('#demo').pagination({
 31                     dataSource: function(done){
 32                         var result = [];
 33                         for (var i = 1; i < pageCount; i++) {
 34                             result.push(i);
 35                         }
 36                         done(result);
 37                     },
 38                     pageCount:pageCount,
 39                     pageSize: 5,
 40                     showGoInput: true,
 41                     showGoButton: true,
 42                     callback: function(data, pagination) {
 43                         // template method of yourself
 44                         var html = template(data);
 45                         dataContainer.html(html);
 46                     }
 47                 })
 48             } else {
 49                 txt = '';
 50             }
 51 
 52         }
 53     })
 54     function GoHead() {
 55         GoPage(1);
 56     }
 57     function NextClick() {
 58         if (pageIndex < pageCount) {
 59             pageIndex = pageIndex + 1;
 60         } else {
 61             pageIndex = pageCount;
 62         }
 63         GoPage(pageIndex);
 64         $("#pageCurrent").html(pageIndex);
 65     }
 66 
 67     function backClick() {
 68         if (pageIndex > 1) {
 69             pageIndex = pageIndex - 1;
 70             GoPage(pageIndex);
 71             $("#pageCurrent").html(pageIndex);
 72         }
 73     }
 74     function GoPageNew() {
 75         var page=$("#pageGo").val();
 76         GoPage(page);
 77         opts.current=page;
 78     }
 79     function GoPage(pageIndex) {
 80         if(pageIndex==0) {
 81             pageIndexStr = $('#goPage').val();
 82             if (pageIndexStr==undefined) {
 83                 return false;
 84             }
 85             pageIndexStr = pageIndexStr.trim();
 86             var pageIndex = parseInt(pageIndexStr);
 87         }
 88         $('#page'+pageIndex).siblings().removeClass('active');
 89         $('#page'+pageIndex).addClass('active');
 90 
 91         if (pageIndex==1) {
 92             if(!$('#backClick').hasClass('disabled')) {
 93                 $('#backClick').addClass('disabled');
 94             }
 95         } else {
 96             $('#backClick').removeClass('disabled');
 97         }
 98         if (pageIndex == pageCount) {
 99             if(!$('#nextClick').hasClass('disabled')) {
100                 $('#nextClick').addClass('disabled');
101             }
102         } else {
103             $('#nextClick').removeClass('disabled');
104         }
105         var pageTxt = txt.substring((pageIndex - 1) * pageSize, pageIndex * pageSize);
106         $('#word').html(TransferString(pageTxt));
107         $('html, body').animate({
108             'scrollTop': 0
109         }, 0);
110         $("#pageCurrent").html(pageIndex);
111     }
112     function PageGo(){
113         if($('.jump-ipt').val()!=''){
114             GoPage($('.jump-ipt').val())
115         }
116     }
JavaScript Code
 1 @{
 2     if (null != ViewBag.Ariticle)
 3     {
 4         DataRow dr = ViewBag.Ariticle;
 5         if (null != dr)
 6         {
 7             ViewBag.Title = dr["Title"];
 8             <div class="container">
 9                 <div class="row">
10                     <div class="col-xs-12">
11                         <div class="breadcrumb_block">
12                             <span class="tit"><a href="/web/sciencefiction/index">科普IP</a> &gt;</span>
13                             <ol class="breadcrumb">
14                                 <li class="active">@dr["Title"]</li>
15                                 <li class="active">在線試讀</li>
16                             </ol>
17                             <div class="clear"></div>
18                         </div>
19                     </div>
20                     <div class="col-sm-8">
21                         <input type="hidden" name="aId" id="aId" value="@Request["id"]" />
22                         <div class="read_book">
23                             <h3 class="read_tit">@dr["Title"]</h3>
24                             <div class="author">
25                                 <span class="ml30"><em id="pageCurrent">1</em>/<em id="PageCount">0</em></span>
26                             </div>
27                             <input type="hidden" value="@dr["FilePath"]" id="urlArticleContent">
28                             <div class="word" id="word">
29 
30                         <nav class="page-my">
31                             <ul class="pagination pull-right fs14" id="demo"></ul>
32                             <div class="clear"></div>
33                         </nav>
34                         <!--底部翻頁-->
35                     </div>
36                     <div class="col-sm-3">
37                         <input type="hidden" name="pageCount" id="pageCount" value="@ViewBag.pageCount" />
38                         <!--閱讀控制-->
39                         <div class="read_control">
40                             <a href="javascript:;" onclick="backClick()"><span class="icon icon01"></span><em>上一頁</em></a>
41                             <a href="javascript:;" onclick="NextClick()"><span class="icon icon02"></span><em>下一頁</em></a>
42                             <a href="javascript:;" onclick="GoHead()"><span class="icon icon03"></span><em>回首頁</em></a>
43                         </div>
44                     </div>
45                 </div>
46             </div>
47         }
48     }
49 }
View Code

txt文件上傳時需要做一些處理,否則只能顯示UTF8格式的txt

 1 /// <summary>
 2         /// 文件上傳
 3         /// </summary>
 4         /// <returns></returns>
 5         public JsonResult UploadFiles()
 6         {
 7 
 8             HttpPostedFileBase postFile = HttpContext.Request.Files["filesave"];
 9             if (postFile != null)
10             {
11                 string fileName = Path.GetFileName(postFile.FileName);
12                 string fileExt = Path.GetExtension(fileName.ToLower());
13                 string fileSize = postFile.ContentLength.ToString();
14                 long fileNameTem = Common.GenerateLongId();
15                 string sPath = string.Format("/Data/Material/{0}_{1}.txt", fileNameTem.ToString(), fileName.Replace(".txt", ""));//Guid.NewGuid().ToString().Replace("-", "")
16                 string viewUrl = string.Empty;
17                 string g = Guid.NewGuid().ToString();
18                 if (!Directory.Exists(Server.MapPath("~") + "/Data/Material"))
19                     Directory.CreateDirectory(Server.MapPath("~") + "/Data/Material");
20                 string p = Server.MapPath(sPath);
21                 postFile.SaveAs(p);
22 
23                 if (System.IO.File.Exists(p))
24                 {
25                     StreamReader sr = new StreamReader(p, System.Text.Encoding.Default);
26                     String input = sr.ReadToEnd();
27                     sr.Close();
28 
29                     StreamWriter sw = new StreamWriter(p, false, System.Text.Encoding.UTF8);
30                     sw.WriteLine(input);
31                     sw.Close();
32                 }
33                 return Json(new { FilePath = sPath, FileName = fileName, viewurl = viewUrl, fileSize = fileSize });
34             }
35             else
36             {
37                 return Json(new { FilePath = "" });
38             }
39         }
C# Code

效果圖:

 

 

另外頁面首頁引入js

<script src="~/Scripts/web/jquery.pagination.js"></script>
<link href="~/Content/jquery.pagination.css" rel="stylesheet" />

  1 /**
  2  * pagination分頁插件
  3  * @version 1.1.2
  4  * @author mss
  5  * @url http://maxiaoxiang.com/plugin/pagination.html
  6  * @E-mail [email protected]
  7  *
  8  * @調用方法
  9  * $(selector).pagination();
 10  * 
 11  * @更新日志
 12  * 2016-07-25:修復click重復事件
 13  */
 14 ; (function ($, window, document, undefined) {
 15 
 16     //配置參數
 17     var defaults = {
 18         totalData: 0,            //數據總條數
 19         showData: 0,                //每頁顯示的條數
 20         pageCount: 9,            //總頁數,默認為9
 21         current: 1,                //當前第幾頁
 22         prevCls: 'prev',            //上一頁class
 23         nextCls: 'next',            //下一頁class
 24         prevContent: '上一頁',        //上一頁內容
 25         nextContent: '下一頁',        //下一頁內容
 26         activeCls: 'active',        //當前頁選中狀態
 27         coping: false,            //首頁和尾頁
 28         homePage: '',            //首頁節點內容
 29         endPage: '',                //尾頁節點內容
 30         count: 5,                //當前頁前後分頁個數
 31         jump: true,                //跳轉到指定頁數
 32         jumpIptCls:  'jump-ipt',    //文本框內容
 33         jumpBtnCls: 'jump-btn',    //跳轉按鈕
 34         jumpBtn: '跳轉',            //跳轉按鈕文本
 35         callback: function () { 
 36         }    //回調
 37     };
 38 
 39     var Pagination = function (element, options) {
 40         //全局變量
 41         var opts = options,//配置
 42             current,//當前頁
 43             $document = $(document),
 44             $obj = $(element);//容器
 45 
 46         /**
 47          * 設置總頁數
 48          * @param int page 頁碼
 49          * @return opts.pageCount 總頁數配置
 50          */
 51         this.setTotalPage = function (page) {
 52             return opts.pageCount = page;
 53         };
 54 
 55         /**
 56          * 獲取總頁數
 57          * @return int p 總頁數
 58          */
 59         this.getTotalPage = function () {
 60             var p = opts.totalData || opts.showData ? Math.ceil(parseInt(opts.totalData) / opts.showData) : opts.pageCount;
 61             return p;
 62         };
 63 
 64         //獲取當前頁
 65         this.getCurrent = function () {
 66             return current;
 67         };
 68 
 69         /**
 70          * 填充數據
 71          * @param int index 頁碼
 72          */
 73         this.filling = function (index) {
 74             var html = '';
 75             current = index || opts.current;//當前頁碼
 76             var pageCount = this.getTotalPage();
 77             if (current > 1) {//上一頁
 78                 html += '<li onclick=GoPage(' + (current - 1) + ')><a href="javascript:;" class="' + opts.prevCls + '">' + opts.prevContent + '</a></li>';
 79             } else {
 80                 $obj.find('.' + opts.prevCls) && $obj.find('.' + opts.prevCls).remove();
 81             }
 82             if (current >= opts.count * 2 && current != 1 && pageCount != opts.count) {
 83                 var home = opts.coping && opts.homePage ? opts.homePage : '1';
 84                 html += opts.coping ? '<li onclick=GoPage(' + home + ')><a href="javascript:;" data-page="1">' + home + '</a></li><span>...</span>' : '';
 85             }
 86             var start = current - opts.count,
 87                 end = current + opts.count;
 88             ((start > 1 && current < opts.count) || current == 1) && end++;
 89             (current > pageCount - opts.count && current >= pageCount) && start++;
 90             for (; start <= end; start++) {
 91                 if (start <= pageCount && start >= 1) {
 92                     if (start != current) {
 93                         html += '<li onclick=GoPage(' + start + ')><a href="javascript:;" data-page="' + start + '">' + start + '</a></li>';
 94                     } else {
 95                         html += '<li class="' + opts.activeCls + '" onclick=GoPage(' + start + ')><a href="javascript:;"><span>' + start + '</span></a></li>';
 96                     }
 97                 }
 98             }
 99             if (current + opts.count < pageCount && current >= 1 && pageCount > opts.count) {
100                 var end = opts.coping && opts.endPage ? opts.endPage : pageCount;
101                 html += opts.coping ? '<span>...</span><li onclick=GoPage(' + pageCount + ')><a href="javascript:;" data-page="' + pageCount + '">' + end + '</a></li>' : '';
102             }
103             if (current < pageCount) {//下一頁
104                 html += '<li onclick=GoPage(' + (current + 1) + ')><a href="javascript:;" class="' + opts.nextCls + '">' + opts.nextContent + '</a></li>'
105             } else {
106                 $obj.find('.' + opts.nextCls) && $obj.find('.' + opts.nextCls).remove();
107             }
108 
109             html += opts.jump ? '<input type="text"  class="' + opts.jumpIptCls + '"><a href="javascript:;" onclick=PageGo() class="' + opts.jumpBtnCls + '">' + opts.jumpBtn + '</a>' : '';
110 
111             $obj.empty().html(html);
112         };
113 
114         //綁定事件
115         this.eventBind = function () {
116             var self = this;
117             var pageCount = this.getTotalPage();//總頁數
118             $obj.off().on('click', 'a', function () {
119                 if ($(this).hasClass(opts.nextCls)) {
120                     var index = parseInt($obj.find('.' + opts.activeCls).text()) + 1;
121                 } else if ($(this).hasClass(opts.prevCls)) {
122                     var index = parseInt($obj.find('.' + opts.activeCls).text()) - 1;
123                 } else if ($(this).hasClass(opts.jumpBtnCls)) {
124                     if ($obj.find('.' + opts.jumpIptCls).val() !== '') {
125                         var index = parseInt($obj.find('.' + opts.jumpIptCls).val());
126                     } else {
127                         return;
128                     }
129                 } else {
130                     var index = parseInt($(this).data('page'));
131                 }
132                 self.filling(index);
133                 typeof opts.callback === 'function' && opts.callback(self);
134             });
135             //輸入跳轉的頁碼
136             $obj.on('input propertychange', '.' + opts.jumpIptCls, function () {
137                 var $this = $(this);
138                 var val = $this.val();
139                 var reg = /[^\d]/g;
140                 if (reg.test(val)) {
141                     $this.val(val.replace(reg, ''));
142                 }
143                 (parseInt(val) > pageCount) && $this.val(pageCount);
144                 if (parseInt(val) === 0) {//最小值為1
145                     $this.val(1);
146                 }
147             });
148             //回車跳轉指定頁碼
149             $document.keydown(function (e) {
150                 var self = this;
151                 if (e.keyCode == 13 && $obj.find('.' + opts.jumpIptCls).val()) {
152                     var index = parseInt($obj.find('.' + opts.jumpIptCls).val());
153                     GoPage(index);
154                     //self.filling(index);
155                     //typeof opts.callback === 'function' && opts.callback(self);
156                 }
157             });
158         };
159 
160         //初始化
161         this.init = function () {
162             this.filling(opts.current);
163             this.eventBind();
164         };
165         this.init();
166     };
167 
168     $.fn.pagination = function (parameter, callback) {
169         if (typeof parameter == 'function') {//重載
170             callback = parameter;
171             parameter = {};
172         } else {
173             parameter = parameter || {};
174             callback = callback || function () { };
175         }
176         var options = $.extend({}, defaults, parameter);
177         return this.each(function () {
178             var pagination = new Pagination(this, options);
179             callback(pagination);
180         });
181     };
182 
183 })(jQuery, window, document);
Jquery.pagination.js Code

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved