Ajax读取txt并对txt内容进行分页显示功能
下文给大家分享了ajax读取txt并对txt内容进行分页显示的核心代码,废话不多说了,直接贴代码了。
functionTransferString(content) { varstring=content; try{ string=string.replace(/\r\n/g,"<BR>") string=string.replace(/\n/g,"<BR>"); string=string.replace(/[]/g," ") string=string.replace(/\+/g," ") }catch(e){ alert(e.message); } returnstring; } varpageIndex=1; varid=$("#aId").val(); varurl=$('#urlArticleContent').val(); vartxt=''; varpageSize=@(ConfigurationManager.AppSettings["ArticlepageSize"]); varpage=5; varpageCount=0; $(function(){ if(url!="") { txt=($.ajax({url:url,async:false})).responseText; if(txt.indexOf('http://www.w3.org/1999/xhtml')==-1){ pageCount=Math.ceil(txt.length/pageSize); $("#PageCount").html(pageCount); $('#word').html(TransferString(txt.substring(0,pageSize))); $('#demo').pagination({ dataSource:function(done){ varresult=[]; for(vari=1;i<pageCount;i++){ result.push(i); } done(result); }, pageCount:pageCount, pageSize:5, showGoInput:true, showGoButton:true, callback:function(data,pagination){ //templatemethodofyourself varhtml=template(data); dataContainer.html(html); } }) }else{ txt=''; } } }) functionGoHead(){ GoPage(1); } functionNextClick(){ if(pageIndex<pageCount){ pageIndex=pageIndex+1; }else{ pageIndex=pageCount; } GoPage(pageIndex); $("#pageCurrent").html(pageIndex); } functionbackClick(){ if(pageIndex>1){ pageIndex=pageIndex-1; GoPage(pageIndex); $("#pageCurrent").html(pageIndex); } } functionGoPageNew(){ varpage=$("#pageGo").val(); GoPage(page); opts.current=page; } functionGoPage(pageIndex){ if(pageIndex==0){ pageIndexStr=$('#goPage').val(); if(pageIndexStr==undefined){ returnfalse; } pageIndexStr=pageIndexStr.trim(); varpageIndex=parseInt(pageIndexStr); } $('#page'+pageIndex).siblings().removeClass('active'); $('#page'+pageIndex).addClass('active'); if(pageIndex==1){ if(!$('#backClick').hasClass('disabled')){ $('#backClick').addClass('disabled'); } }else{ $('#backClick').removeClass('disabled'); } if(pageIndex==pageCount){ if(!$('#nextClick').hasClass('disabled')){ $('#nextClick').addClass('disabled'); } }else{ $('#nextClick').removeClass('disabled'); } varpageTxt=txt.substring((pageIndex-1)*pageSize,pageIndex*pageSize); $('#word').html(TransferString(pageTxt)); $('html,body').animate({ 'scrollTop':0 },0); $("#pageCurrent").html(pageIndex); } functionPageGo(){if($('.jump-ipt').val()!=''){ GoPage($('.jump-ipt').val()) } } @{ if(null!=ViewBag.Ariticle) { DataRowdr=ViewBag.Ariticle; if(null!=dr) { ViewBag.Title=dr["Title"]; <divclass="container"> <divclass="row"> <divclass="col-xs-12"> <divclass="breadcrumb_block"> <spanclass="tit"><ahref="/web/sciencefiction/index">科普IP</a>></span> <olclass="breadcrumb"> <liclass="active">@dr["Title"]</li> <liclass="active">在线试读</li> </ol> <divclass="clear"></div> </div> </div> <divclass="col-sm-8"> <inputtype="hidden"name="aId"id="aId"value="@Request["id"]"/> <divclass="read_book"> <h3class="read_tit">@dr["Title"]</h3> <divclass="author"> <spanclass="ml30"><emid="pageCurrent">1</em>/<emid="PageCount">0</em></span> </div> <inputtype="hidden"value="@dr["FilePath"]"id="urlArticleContent"> <divclass="word"id="word"> <navclass="page-my"> <ulclass="paginationpull-rightfs14"id="demo"></ul> <divclass="clear"></div> </nav> <!--底部翻页--> </div> <divclass="col-sm-3"> <inputtype="hidden"name="pageCount"id="pageCount"value="@ViewBag.pageCount"/> <!--阅读控制--> <divclass="read_control"> <ahref="javascript:;"onclick="backClick()"><spanclass="iconicon01"></span><em>上一页</em></a> <ahref="javascript:;"onclick="NextClick()"><spanclass="iconicon02"></span><em>下一页</em></a> <ahref="javascript:;"onclick="GoHead()"><spanclass="iconicon03"></span><em>回首页</em></a> </div> </div> </div> </div> } } }
txt文件上传时需要做一些处理,否则只能显示UTF8格式的txt
///<summary> ///文件上传 ///</summary> ///<returns></returns> publicJsonResultUploadFiles() { HttpPostedFileBasepostFile=HttpContext.Request.Files["filesave"]; if(postFile!=null) { stringfileName=Path.GetFileName(postFile.FileName); stringfileExt=Path.GetExtension(fileName.ToLower()); stringfileSize=postFile.ContentLength.ToString(); longfileNameTem=Common.GenerateLongId(); stringsPath=string.Format("/Data/Material/{0}_{1}.txt",fileNameTem.ToString(),fileName.Replace(".txt",""));//Guid.NewGuid().ToString().Replace("-","") stringviewUrl=string.Empty; stringg=Guid.NewGuid().ToString(); if(!Directory.Exists(Server.MapPath("~")+"/Data/Material")) Directory.CreateDirectory(Server.MapPath("~")+"/Data/Material"); stringp=Server.MapPath(sPath); postFile.SaveAs(p); if(System.IO.File.Exists(p)) { StreamReadersr=newStreamReader(p,System.Text.Encoding.Default); Stringinput=sr.ReadToEnd(); sr.Close(); StreamWritersw=newStreamWriter(p,false,System.Text.Encoding.UTF8); sw.WriteLine(input); sw.Close(); } returnJson(new{FilePath=sPath,FileName=fileName,viewurl=viewUrl,fileSize=fileSize}); } else { returnJson(new{FilePath=""}); } }
另外页面首页引入js
<scriptsrc="~/Scripts/web/jquery.pagination.js"></script> <linkhref="~/Content/jquery.pagination.css"rel="stylesheet"/> /** *pagination分页插件 *@version1.1.2 *@authormss *@urlhttp://maxiaoxiang.com/plugin/pagination.html *@E-mail251445460@qq.com * *@调用方法 *$(selector).pagination(); * *@更新日志 *2016-07-25:修复click重复事件 */ ;(function($,window,document,undefined){ //配置参数 vardefaults={ totalData:0,//数据总条数 showData:0,//每页显示的条数 pageCount:9,//总页数,默认为9 current:1,//当前第几页 prevCls:'prev',//上一页class nextCls:'next',//下一页class prevContent:'上一页',//上一页内容 nextContent:'下一页',//下一页内容 activeCls:'active',//当前页选中状态 coping:false,//首页和尾页 homePage:'',//首页节点内容 endPage:'',//尾页节点内容 count:5,//当前页前后分页个数 jump:true,//跳转到指定页数 jumpIptCls:'jump-ipt',//文本框内容 jumpBtnCls:'jump-btn',//跳转按钮 jumpBtn:'跳转',//跳转按钮文本 callback:function(){ }//回调 }; varPagination=function(element,options){ //全局变量 varopts=options,//配置 current,//当前页 $document=$(document), $obj=$(element);//容器 /** *设置总页数 *@paramintpage页码 *@returnopts.pageCount总页数配置 */ this.setTotalPage=function(page){ returnopts.pageCount=page; }; /** *获取总页数 *@returnintp总页数 */ this.getTotalPage=function(){ varp=opts.totalData||opts.showData?Math.ceil(parseInt(opts.totalData)/opts.showData):opts.pageCount; returnp; }; //获取当前页 this.getCurrent=function(){ returncurrent; }; /** *填充数据 *@paramintindex页码 */ this.filling=function(index){ varhtml=''; current=index||opts.current;//当前页码 varpageCount=this.getTotalPage(); if(current>1){//上一页 html+='<lionclick=GoPage('+(current-1)+')><ahref="javascript:;"class="'+opts.prevCls+'">'+opts.prevContent+'</a></li>'; }else{ $obj.find('.'+opts.prevCls)&&$obj.find('.'+opts.prevCls).remove(); } if(current>=opts.count*2&¤t!=1&&pageCount!=opts.count){ varhome=opts.coping&&opts.homePage?opts.homePage:'1'; html+=opts.coping?'<lionclick=GoPage('+home+')><ahref="javascript:;"data-page="1">'+home+'</a></li><span>...</span>':''; } varstart=current-opts.count, end=current+opts.count; ((start>1&¤t<opts.count)||current==1)&&end++; (current>pageCount-opts.count&¤t>=pageCount)&&start++; for(;start<=end;start++){ if(start<=pageCount&&start>=1){ if(start!=current){ html+='<lionclick=GoPage('+start+')><ahref="javascript:;"data-page="'+start+'">'+start+'</a></li>'; }else{ html+='<liclass="'+opts.activeCls+'"onclick=GoPage('+start+')><ahref="javascript:;"><span>'+start+'</span></a></li>'; } } } if(current+opts.count<pageCount&¤t>=1&&pageCount>opts.count){ varend=opts.coping&&opts.endPage?opts.endPage:pageCount; html+=opts.coping?'<span>...</span><lionclick=GoPage('+pageCount+')><ahref="javascript:;"data-page="'+pageCount+'">'+end+'</a></li>':''; } if(current<pageCount){//下一页 html+='<lionclick=GoPage('+(current+1)+')><ahref="javascript:;"class="'+opts.nextCls+'">'+opts.nextContent+'</a></li>' }else{ $obj.find('.'+opts.nextCls)&&$obj.find('.'+opts.nextCls).remove(); } html+=opts.jump?'<inputtype="text"class="'+opts.jumpIptCls+'"><ahref="javascript:;"onclick=PageGo()class="'+opts.jumpBtnCls+'">'+opts.jumpBtn+'</a>':''; $obj.empty().html(html); }; //绑定事件 this.eventBind=function(){ varself=this; varpageCount=this.getTotalPage();//总页数 $obj.off().on('click','a',function(){ if($(this).hasClass(opts.nextCls)){ varindex=parseInt($obj.find('.'+opts.activeCls).text())+1; }elseif($(this).hasClass(opts.prevCls)){ varindex=parseInt($obj.find('.'+opts.activeCls).text())-1; }elseif($(this).hasClass(opts.jumpBtnCls)){ if($obj.find('.'+opts.jumpIptCls).val()!==''){ varindex=parseInt($obj.find('.'+opts.jumpIptCls).val()); }else{ return; } }else{ varindex=parseInt($(this).data('page')); } self.filling(index); typeofopts.callback==='function'&&opts.callback(self); }); //输入跳转的页码 $obj.on('inputpropertychange','.'+opts.jumpIptCls,function(){ var$this=$(this); varval=$this.val(); varreg=/[^\d]/g; if(reg.test(val)){ $this.val(val.replace(reg,'')); } (parseInt(val)>pageCount)&&$this.val(pageCount); if(parseInt(val)===0){//最小值为1 $this.val(1); } }); //回车跳转指定页码 $document.keydown(function(e){ varself=this; if(e.keyCode==13&&$obj.find('.'+opts.jumpIptCls).val()){ varindex=parseInt($obj.find('.'+opts.jumpIptCls).val()); GoPage(index); //self.filling(index); //typeofopts.callback==='function'&&opts.callback(self); } }); }; //初始化 this.init=function(){ this.filling(opts.current); this.eventBind(); }; this.init(); }; $.fn.pagination=function(parameter,callback){ if(typeofparameter=='function'){//重载 callback=parameter; parameter={}; }else{ parameter=parameter||{}; callback=callback||function(){}; } varoptions=$.extend({},defaults,parameter); returnthis.each(function(){ varpagination=newPagination(this,options); callback(pagination); }); }; })(jQuery,window,document);
以上所述是小编给大家介绍的Ajax读取txt并对txt内容进行分页显示,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!