原理与示例:php+mysql+jquery 生成静态网页(含后台编辑功能)
从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>
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));?>
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>
|
|
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("
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("
$(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("
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");?>
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");?>
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));?>
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");?>
11、模板文件:template/t1.html
<meta charset="utf-8"> <title>{TITLE}</title> <a href="../index.html">返回列表页</a> <div>{CONTENT}</div>
结果:
前台:
前台打开链接后:
后台首页:
添加记录:
添加后:
修改记录:
删除记录:
删除后的列表:

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



Alipay PHP...

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,

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 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? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

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

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�...

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.
