Ajax reads txt and displays the txt content in pages
This article introduces you to the function of Ajax reading txt and paginating the txt content. It is very good and has the value of reference and learning ajax. Friends who are interested in ajax should take a look.
Below I will share with you the core code for ajax to read txt and display the txt content in pages. Without further ado, I will post the code directly.
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"]; <p class="container"> <p class="row"> <p class="col-xs-12"> <p 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> <p class="clear"></p> </p> </p> <p class="col-sm-8"> <input type="hidden" name="aId" id="aId" value="@Request["id"]" /> <p class="read_book"> <h3 class="read_tit">@dr["Title"]</h3> <p class="author"> <span class="ml30"><em id="pageCurrent">1</em>/<em id="PageCount">0</em></span> </p> <input type="hidden" value="@dr["FilePath"]" id="urlArticleContent"> <p class="word" id="word"> <nav class="page-my"> <ul class="pagination pull-right fs14" id="demo"></ul> <p class="clear"></p> </nav> <!--底部翻页--> </p> <p class="col-sm-3"> <input type="hidden" name="pageCount" id="pageCount" value="@ViewBag.pageCount" /> <!--阅读控制--> <p 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> </p> </p> </p> </p> } } }
Some processing is required when uploading the txt file, otherwise only the txt in UTF8 format can be displayed
/// <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 = "" }); } }
In addition, the homepage of the page introduces 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);
The above is the Ajax introduced by the editor to read txt and display the txt content in pages. I hope it will be helpful to everyone! !
Related recommendations:
Ajax simple real-time verification function implementation method
Native JS implements ajax and ajax cross-domain requests
JS implements Ajax cross-domain request flask response content
The above is the detailed content of Ajax reads txt and displays the txt content in pages. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to change the page that opens the Microsoft Edge browser to 360 navigation? It is actually very simple, so now I will share with you the method of changing the page that opens the Microsoft Edge browser to 360 navigation. Friends in need can take a look. I hope Can help everyone. Open the Microsoft Edge browser. We see a page like the one below. Click the three-dot icon in the upper right corner. Click "Settings." Click "On startup" in the left column of the settings page. Click on the three points shown in the picture in the right column (do not click "Open New Tab"), then click Edit and change the URL to "0" (or other meaningless numbers). Then click "Save". Next, select "

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

CheatEngine is a game editor that can edit and modify the game's memory. However, its default language is non-Chinese, which is inconvenient for many friends. So how to set Chinese in CheatEngine? Today, the editor will give you a detailed introduction to how to set up Chinese in CheatEngine. I hope it can help you. Setting method one: 1. Double-click to open the software and click "edit" in the upper left corner. 2. Then click “settings” in the option list below. 3. In the opened window interface, click "languages" in the left column

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Do you know where to set the download button to display in Microsoft Edge? Below, the editor will bring you the method to set the download button to display in Microsoft Edge. I hope it will be helpful to you. Let’s follow the editor to learn it! Step 1: First open Microsoft Edge Browser, click the [...] logo in the upper right corner, as shown in the figure below. Step 2: Then click [Settings] in the pop-up menu, as shown in the figure below. Step 3: Then click [Appearance] on the left side of the interface, as shown in the figure below. Step 4: Finally, click the button on the right side of [Show Download Button] and it will change from gray to blue, as shown in the figure below. The above is where the editor brings you how to set up the download button in Microsoft Edge.
