search
HomeWeb Front-endJS TutorialHow to read txt with Ajax and display its content in pages

This time I will show you how Ajax reads txt and displays its content in pages. How Ajax reads txt and displays its content in pages. What are the precautions? . The following is a practical case. , let’s take a look.

The following 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  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>
</p><p>
</p><p>
</p><p>
<span><a>科普IP</a> ></span>
</p><ol>
<li>@dr["Title"]</li>
<li>在线试读</li>
</ol>
<p></p>


<p>
<input>
</p><p>
</p><h3 id="dr-Title">@dr["Title"]</h3>
<p>
<span><em>1</em>/<em>0</em></span>
</p>
<input>
<p>
<nav>
<ul></ul>
<p></p>
</nav>
<!--底部翻页-->
</p>
<p>
<input>
<!--阅读控制-->
</p><p>
<a><span></span><em>上一页</em></a>
<a><span></span><em>下一页</em></a>
<a><span></span><em>回首页</em></a>
</p>



}
}
}

txtSome processing needs to be done when uploading the file, otherwise only 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, js is introduced on the home page of the page

<script></script>
<link>
/**
* 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 += '
  • ' + opts.prevContent + '
  • '; } 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 ? '
  • ' + home + '
  • ...' : ''; } var start = current - opts.count, end = current + opts.count; ((start > 1 && current  pageCount - opts.count && current >= pageCount) && start++; for (; start = 1) { if (start != current) { html += '
  • ' + start + '
  • '; } else { html += '
  • ' + start + '
  • '; } } } if (current + opts.count = 1 && pageCount > opts.count) { var end = opts.coping && opts.endPage ? opts.endPage : pageCount; html += opts.coping ? '...
  • ' + end + '
  • ' : ''; } if (current ' + opts.nextContent + '' } else { $obj.find('.' + opts.nextCls) && $obj.find('.' + opts.nextCls).remove(); } html += opts.jump ? '' + opts.jumpBtn + '' : ''; $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);

    I believe it After reading the case in this article, you have mastered the method. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

    Recommended reading:

    How to implement AJAX request array

    How to implement AJAX queue request (with code)

    The above is the detailed content of How to read txt with Ajax and display its content in pages. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

    Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

    Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

    The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

    The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

    JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

    Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

    JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

    The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

    The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

    Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

    Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

    Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

    Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

    JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

    JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

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

    Hot Tools

    ZendStudio 13.5.1 Mac

    ZendStudio 13.5.1 Mac

    Powerful PHP integrated development environment

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    MinGW - Minimalist GNU for Windows

    MinGW - Minimalist GNU for Windows

    This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.