Home Backend Development PHP Tutorial 原理与示例:php+mysql+jquery 生成静态网页(含后台编辑功能)

原理与示例:php+mysql+jquery 生成静态网页(含后台编辑功能)

Jun 23, 2016 pm 01:42 PM

从Web的工作原理来看,用户访问HTML所带来的服务器负载要远小于访问动态页面,因为在前者中,服务器只用把对应的html代码发送给客户端即可,而在后者中,服务器则需要根据访问条件进行一系列的计算,然后生成html代码,最后把运算结果代码发送给客户端。 所以,对于访问量较大的宣传式网站(比如新闻类),要尽可能地使用静态页面。

另一方面,我们不可能让网站编辑人员来一个一个地手工制作这些HTML,那样就是回到多年前的纯静态时代了。我们可以用动态语言来方便、快捷地生成这些静态网页。而且,目前这一技术已经十分成熟。本文仅以最简单的原理和案例着手,试图讲明白大致的方法和流程,不关心具体的细节(比如文本编辑器)。

原理步骤:

1、制作一个内容为空的html页面,作为模板。

2、当网站编辑人员通过后台添加一条记录时,将其内容添加到模板文件的相应的位置上,然后将其保存为特定位置的html文件

3、在数据库中记录下该文件的信息

4、在前台,读取数据库中的记录并显示

5、后台编辑,本质上是对html文件的增、删、改,顺带对数据库中的记录也进行如上操作。


目录结构:


数据库设计:

create database cms_php_html;

use cms_php_html;

CREATE TABLE IF NOT EXISTS `newslist` (
 
 `nID` int(11) NOT NULL AUTO_INCREMENT,
 
`nTitle` varchar(50) COLLATE utf8_bin NOT NULL,
 
`nURL` varchar(100) COLLATE utf8_bin NOT NULL,
 
 PRIMARY KEY (`nID`)

) ENGINE=InnoDB  DEFAULT CHARSET=utf8 ;


代码:

1、前台首页: index.html

			<meta charset="utf-8">		<title>NewsList</title>		<script src="js/jquery-1.8.2.min.js" type="text/javascript" charset="utf-8"></script>		<script src="js/query.js" type="text/javascript" charset="utf-8"></script>		<script>					$(function(){				$.ajax({					type:"get",					url:"admin/query.php",					dataType:"json",					success:function(data){						$("#newsList").html();						$.each(data, function(index,row) { 										$("#newsList").append("<li><a href='"+ row['nURL']+"'>"+row['nTitle']+"");									});							}				});							})		</script>				
Copy after login

2、前台查询数据库页面:admin/query.php

<?phpmysql_connect ("localhost","root","root");mysql_query("set names utf8");mysql_select_db("cms_php_html");$myrs=mysql_query("select * from newsList order by nID");while($row=mysql_fetch_array($myrs)){	$temp[]=$row;}echo(json_encode($temp));?>
Copy after login

3、后台编辑首页:admin/admin_index.html

			<meta charset="utf-8">		<title>CMS后台</title>		<script src="../js/jquery-1.8.2.min.js" type="text/javascript" charset="utf-8"></script>		<script type="text/javascript" src="../js/new.js"></script>		<!--<script src="../js/query.js" type="text/javascript" charset="utf-8"></script>-->		<script src="../js/saveEdit.js" type="text/javascript" charset="utf-8"></script>		<script src="../js/delete.js" type="text/javascript" charset="utf-8"></script>				<div><a href="../index.html" target="_blank">前台查看</a></div>		
Copy after login
  • 添加
  • 标题:
  • 内容:
  •   
  • 修改
  • 文件:
  • 标题:
  • 内容:
  •      
News List

4、与新增记录、修改记录有关的js:js/new.js

$(function() {	//首先在表格正文列出已有记录	$.ajax({		type:"get",		url:"../admin/query.php",		dataType:"json",		success:function(data){			$("#newsList").html("");			$.each(data, function(index,row) { 					$("#newsList").append("
Copy after login
  • "+row['nTitle']+"
  • "); }); $("#newsList li").each(function(){ $(this).bind('click',{url:$(this).attr('title')},readNews) }) } }); //清空新增记录的文本框 $("#newClear").click(function(){ newTitle=$("#newTitle").val("") newContent=$("#newContent").val(""); }) //清空修改记录的文本框 $("#editClear").click(function(){ newTitle=$("#oldTitle").val("") newContent=$("#oldContent").val(""); $("#pageFile").html("") }) //提交新增记录内容 $("#newSubmit").click(function(){ if($("#newTitle").val()!="" && $("#newContent").val()!="") { $("#newSubmit").val('添加中..'); $("#newSubmit").attr("disabled","disabled"); newTitle=$("#newTitle").val() newContent=$("#newContent").val(); $.ajax({ type:"post", url:"../admin/new.php", data:{txtTitle:newTitle,txtContent:newContent}, dataType:'html', success:function(data){ alert(data); $("#newSubmit").removeAttr("disabled"); $("#newSubmit").val('添加'); $.ajax({ type:"get", url:"../admin/query.php", dataType:"json", success:function(data){ //新增成功后刷新下方已有记录列表 $("#newsList").html(""); $.each(data, function(index,row) { $("#newsList").append("
  • "+row['nTitle']+"  
  • "); }); $("#newsList li").each(function(){ $(this).bind('click',{url:$(this).attr('title')},readNews) }) } }); } }); } })})//点击记录列表中任一条,会在修改区域的文本框中显示该记录的原有内容function readNews(evt){// alert(evt.data.url); $.ajax({ type:"get", url:"../admin/read.php", dataType:'json', data:{htmlUrl:evt.data.url}, success:function(data){// alert('returned') $("#oldTitle").val(data[0]); $("#oldContent").val(data[1]) $("#pageFile").html(evt.data.url) } });}
    5、与修改记录有关的js:js/saveEdit.js

    $(function(){	$("#oldSubmit").click(function(){		if($("#pageFile").text()!="" && $("#oldTitle").val()!="" && $("#oldContent").val()!="")		{			$("#oldSubmit").val('修改中...');			fileURL=$("#pageFile").html();			$("#oldSubmit").attr("disabled","disabled");			newTitle=$("#oldTitle").val()			newContent=$("#oldContent").val();			$.ajax({				type:"post",				url:"../admin/saveEdit.php",				data:{url:fileURL,title:newTitle,content:newContent},				dataType:'html',				success:function(data){					$("#oldSubmit").removeAttr("disabled");					$("#oldSubmit").val('修改');						alert(data);										$.ajax({						type:"get",						url:"../admin/query.php",						dataType:"json",						success:function(data){							$("#newsList").html("");							$.each(data, function(index,row) { 											$("#newsList").append("
    Copy after login
  • "+row['nTitle']+"  
  • "); }); $("#newsList li").each(function(){ $(this).bind('click',{url:$(this).attr('title')},readNews) }) } }); } }); } })})function readNews(evt){// alert(evt.data.url); $.ajax({ type:"get", url:"../admin/read.php", dataType:'json', data:{htmlUrl:evt.data.url}, success:function(data){// alert('returned') $("#oldTitle").val(data[0]); $("#oldContent").val(data[1]) $("#pageFile").html(evt.data.url) } });}6、与删除记录有关的js:js/delete.js

    $(function(){	$("#oldDelete").click(function(){		if(window.confirm('确定删除?')==true)		{			currentURL=$("#pageFile").text();			$.ajax({				type:"post",				url:"../admin/delete.php",				data:{curl:currentURL},				dataType:'html',				success:function(data){					alert(data);					$.ajax({						type:"get",						url:"../admin/query.php",						dataType:"json",						success:function(data){							$("#newsList").html("");							$.each(data, function(index,row) { 									$("#newsList").append("
    Copy after login
  • "+row['nTitle']+"
  • "); }); $("#newsList li").each(function(){ $(this).bind('click',{url:$(this).attr('title')},readNews) }) } }); } }); } })})
    7、新增记录的php实现代码:admin/new.php

    <?php $title=$_POST['txtTitle'];$content=$_POST['txtContent'];$fopen=fopen("../template/t1.html", "r");$templateContent=fread($fopen, filesize("../template/t1.html"));fclose($fopen);$templateContent=str_replace("{TITLE}",$title,$templateContent);$templateContent=str_replace("{CONTENT}",$content,$templateContent);$htmlName="../html/".date("YmdHis").'.html';$fwrite=fopen($htmlName,"w");   fwrite($fwrite,$templateContent); mysql_connect('localhost','root','root');mysql_query("set names utf8");mysql_select_db('cms_php_html');$url="http://localhost/phpToHtml".substr($htmlName, 2);$insertSql="insert into newsList values(null,'".$title."','".$url."')";mysql_query($insertSql);echo json_encode("ok");?>
    Copy after login

    8、修改现有记录的php实现代码:admin/saveEdit.php

    <?php $url=$_POST['url'];$title=$_POST['title'];$content=$_POST['content'];$oldContent=file_get_contents($url);$newContent=preg_replace("#<title>(.*?)#s", "<title>".$title."</title>", $oldContent);$newContent=preg_replace("#(.*?)#s", "".$content."", $newContent);preg_match("#http://localhost/phpToHtml/(.*?).html#s", $url,$m);$fwrite=fopen("../".$m[1].".html","w");fwrite($fwrite,$newContent); mysql_connect("localhost","root","root");mysql_query("set names utf8");mysql_select_db("cms_php_html");mysql_query("update newsList set nTitle='".$title."' where nURL='".$url."'");echo("ok");?>
    Copy after login

    9、读取已有的某条记录的php实现代码:admin/read.php

    <?php $htmlURL=$_GET['htmlUrl'];$fcontents=file_get_contents($htmlURL);preg_match("#<title>(.*?)#s",$fcontents,$titleMatches);preg_match("#(.*?)#s",$fcontents,$contentMatches);$row[0]=$titleMatches[1];$row[1]=$contentMatches[1];echo(json_encode($row));?>
    Copy after login

    10、删除某条记录的php实现代码:admin/delete.php

    <?php $url=$_POST['curl'];mysql_connect("localhost","root","root");mysql_query("set names utf8");mysql_select_db("cms_php_html");mysql_query("delete from newsList where nURL='".$url."'");echo("ok");?>
    Copy after login

    11、模板文件:template/t1.html

    			<meta charset="utf-8">		<title>{TITLE}</title>				<a href="../index.html">返回列表页</a>		<div>{CONTENT}</div>	
    Copy after login

    结果:

    前台:

    前台打开链接后:

    后台首页:


    添加记录:

    添加后:


    修改记录:


    删除记录:


    删除后的列表:


    Statement of this Website
    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

    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

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

    JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

    Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

    The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

    How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

    How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

    How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

    How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

    Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

    Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

    How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

    Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

    Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

    Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

    See all articles