欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Ajax读取txt并对txt内容进行分页显示功能

程序员文章站 2022-09-05 19:18:53
下文给大家分享了ajax读取txt并对txt内容进行分页显示的核心代码,废话不多说了,直接贴代码了。 function transferstring(cont...

下文给大家分享了ajax读取txt并对txt内容进行分页显示的核心代码,废话不多说了,直接贴代码了。

function transferstring(content)
{
var string = 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);
}
return string;
}
var pageindex = 1;
var id = $("#aid").val();
var url = $('#urlarticlecontent').val();
var txt = '';
var pagesize = @(configurationmanager.appsettings["articlepagesize"]);
var page=5;
var pagecount = 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){
var result = [];
for (var i = 1; i < pagecount; i++) {
result.push(i);
}
done(result);
},
pagecount:pagecount,
pagesize: 5,
showgoinput: true,
showgobutton: true,
callback: function(data, pagination) {
// template method of yourself
var html = template(data);
datacontainer.html(html);
}
})
} else {
txt = '';
}
}
})
function gohead() {
gopage(1);
}
function nextclick() {
if (pageindex < pagecount) {
pageindex = pageindex + 1;
} else {
pageindex = pagecount;
}
gopage(pageindex);
$("#pagecurrent").html(pageindex);
}
function backclick() {
if (pageindex > 1) {
pageindex = pageindex - 1;
gopage(pageindex);
$("#pagecurrent").html(pageindex);
}
}
function gopagenew() {
var page=$("#pagego").val();
gopage(page);
opts.current=page;
}
function gopage(pageindex) {
if(pageindex==0) {
pageindexstr = $('#gopage').val();
if (pageindexstr==undefined) {
return false;
}
pageindexstr = pageindexstr.trim();
var pageindex = 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');
}
var pagetxt = txt.substring((pageindex - 1) * pagesize, pageindex * pagesize);
$('#word').html(transferstring(pagetxt));
$('html, body').animate({
'scrolltop': 0
}, 0);
$("#pagecurrent").html(pageindex);
}
function pagego(){ if($('.jump-ipt').val()!=''){
gopage($('.jump-ipt').val())
}
}
@{
if (null != viewbag.ariticle)
{
datarow dr = viewbag.ariticle;
if (null != dr)
{
viewbag.title = dr["title"];
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="breadcrumb_block">
<span class="tit"><a href="/web/sciencefiction/index">科普ip</a> ></span>
<ol class="breadcrumb">
<li class="active">@dr["title"]</li>
<li class="active">在线试读</li>
</ol>
<div class="clear"></div>
</div>
</div>
<div class="col-sm-8">
<input type="hidden" name="aid" id="aid" value="@request["id"]" />
<div class="read_book">
<h3 class="read_tit">@dr["title"]</h3>
<div class="author">
<span class="ml30"><em id="pagecurrent">1</em>/<em id="pagecount">0</em></span>
</div>
<input type="hidden" value="@dr["filepath"]" id="urlarticlecontent">
<div class="word" id="word">
<nav class="page-my">
<ul class="pagination pull-right fs14" id="demo"></ul>
<div class="clear"></div>
</nav>
<!--底部翻页-->
</div>
<div class="col-sm-3">
<input type="hidden" name="pagecount" id="pagecount" value="@viewbag.pagecount" />
<!--阅读控制-->
<div class="read_control">
<a href="javascript:;" onclick="backclick()"><span class="icon icon01"></span><em>上一页</em></a>
<a href="javascript:;" onclick="nextclick()"><span class="icon icon02"></span><em>下一页</em></a>
<a href="javascript:;" onclick="gohead()"><span class="icon icon03"></span><em>回首页</em></a>
</div>
</div>
</div>
</div>
}
}
}

txt文件上传时需要做一些处理,否则只能显示utf8格式的txt

/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
public jsonresult uploadfiles()
{

httppostedfilebase postfile = httpcontext.request.files["filesave"];
if (postfile != null)
{
string filename = path.getfilename(postfile.filename);
string fileext = path.getextension(filename.tolower());
string filesize = postfile.contentlength.tostring();
long filenametem = common.generatelongid();
string spath = string.format("/data/material/{0}_{1}.txt", filenametem.tostring(), filename.replace(".txt", ""));//guid.newguid().tostring().replace("-", "")
string viewurl = string.empty;
string g = guid.newguid().tostring();
if (!directory.exists(server.mappath("~") + "/data/material"))
directory.createdirectory(server.mappath("~") + "/data/material");
string p = server.mappath(spath);
postfile.saveas(p);

if (system.io.file.exists(p))
{
streamreader sr = new streamreader(p, system.text.encoding.default);
string input = sr.readtoend();
sr.close();

streamwriter sw = new streamwriter(p, false, system.text.encoding.utf8);
sw.writeline(input);
sw.close();
}
return json(new { filepath = spath, filename = filename, viewurl = viewurl, filesize = filesize });
}
else
{
return json(new { filepath = "" });
}
}

另外页面首页引入js

<script src="~/scripts/web/jquery.pagination.js"></script>
<link href="~/content/jquery.pagination.css" rel="stylesheet" />
/**
* pagination分页插件
* @version 1.1.2
* @author mss
* @url http://maxiaoxiang.com/plugin/pagination.html
* @e-mail 251445460@qq.com
*
* @调用方法
* $(selector).pagination();
* 
* @更新日志
* 2016-07-25:修复click重复事件
*/
; (function ($, window, document, undefined) {
//配置参数
var defaults = {
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 () { 
} //回调
};
var pagination = function (element, options) {
//全局变量
var opts = options,//配置
current,//当前页
$document = $(document),
$obj = $(element);//容器
/**
* 设置总页数
* @param int page 页码
* @return opts.pagecount 总页数配置
*/
this.settotalpage = function (page) {
return opts.pagecount = page;
};
/**
* 获取总页数
* @return int p 总页数
*/
this.gettotalpage = function () {
var p = opts.totaldata || opts.showdata ? math.ceil(parseint(opts.totaldata) / opts.showdata) : opts.pagecount;
return p;
};
//获取当前页
this.getcurrent = function () {
return current;
};
/**
* 填充数据
* @param int index 页码
*/
this.filling = function (index) {
var html = '';
current = index || opts.current;//当前页码
var pagecount = this.gettotalpage();
if (current > 1) {//上一页
html += '<li onclick=gopage(' + (current - 1) + ')><a href="javascript:;" class="' + opts.prevcls + '">' + opts.prevcontent + '</a></li>';
} else {
$obj.find('.' + opts.prevcls) && $obj.find('.' + opts.prevcls).remove();
}
if (current >= opts.count * 2 && current != 1 && pagecount != opts.count) {
var home = opts.coping && opts.homepage ? opts.homepage : '1';
html += opts.coping ? '<li onclick=gopage(' + home + ')><a href="javascript:;" data-page="1">' + home + '</a></li><span>...</span>' : '';
}
var start = current - opts.count,
end = current + opts.count;
((start > 1 && current < opts.count) || current == 1) && end++;
(current > pagecount - opts.count && current >= pagecount) && start++;
for (; start <= end; start++) {
if (start <= pagecount && start >= 1) {
if (start != current) {
html += '<li onclick=gopage(' + start + ')><a href="javascript:;" data-page="' + start + '">' + start + '</a></li>';
} else {
html += '<li class="' + opts.activecls + '" onclick=gopage(' + start + ')><a href="javascript:;"><span>' + start + '</span></a></li>';
}
}
}
if (current + opts.count < pagecount && current >= 1 && pagecount > opts.count) {
var end = opts.coping && opts.endpage ? opts.endpage : pagecount;
html += opts.coping ? '<span>...</span><li onclick=gopage(' + pagecount + ')><a href="javascript:;" data-page="' + pagecount + '">' + end + '</a></li>' : '';
}
if (current < pagecount) {//下一页
html += '<li onclick=gopage(' + (current + 1) + ')><a href="javascript:;" class="' + opts.nextcls + '">' + opts.nextcontent + '</a></li>'
} else {
$obj.find('.' + opts.nextcls) && $obj.find('.' + opts.nextcls).remove();
}
html += opts.jump ? '<input type="text" class="' + opts.jumpiptcls + '"><a href="javascript:;" onclick=pagego() class="' + opts.jumpbtncls + '">' + opts.jumpbtn + '</a>' : '';
$obj.empty().html(html);
};
//绑定事件
this.eventbind = function () {
var self = this;
var pagecount = this.gettotalpage();//总页数
$obj.off().on('click', 'a', function () {
if ($(this).hasclass(opts.nextcls)) {
var index = parseint($obj.find('.' + opts.activecls).text()) + 1;
} else if ($(this).hasclass(opts.prevcls)) {
var index = parseint($obj.find('.' + opts.activecls).text()) - 1;
} else if ($(this).hasclass(opts.jumpbtncls)) {
if ($obj.find('.' + opts.jumpiptcls).val() !== '') {
var index = parseint($obj.find('.' + opts.jumpiptcls).val());
} else {
return;
}
} else {
var index = parseint($(this).data('page'));
}
self.filling(index);
typeof opts.callback === 'function' && opts.callback(self);
});
//输入跳转的页码
$obj.on('input propertychange', '.' + opts.jumpiptcls, function () {
var $this = $(this);
var val = $this.val();
var reg = /[^\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) {
var self = this;
if (e.keycode == 13 && $obj.find('.' + opts.jumpiptcls).val()) {
var index = parseint($obj.find('.' + opts.jumpiptcls).val());
gopage(index);
//self.filling(index);
//typeof opts.callback === 'function' && opts.callback(self);
}
});
};
//初始化
this.init = function () {
this.filling(opts.current);
this.eventbind();
};
this.init();
};
$.fn.pagination = function (parameter, callback) {
if (typeof parameter == 'function') {//重载
callback = parameter;
parameter = {};
} else {
parameter = parameter || {};
callback = callback || function () { };
}
var options = $.extend({}, defaults, parameter);
return this.each(function () {
var pagination = new pagination(this, options);
callback(pagination);
});
};
})(jquery, window, document);

以上所述是小编给大家介绍的ajax读取txt并对txt内容进行分页显示,希望对大家有所帮助