An example sharing of front-end and back-end interaction
This week, under the guidance of the master, Ben K completed a small example of a message board function that combines ajax and php file upload processing. Now let Ben K Let me show you how to implement this function.
1. Interface Overview
First, let’s take a look at the specific effect of this small demo.
This demo mainly includes three steps, which also correspond to three functions, namely Registration, login and message boardFunction. These three functions basically rely on several front-end and back-end interaction technologies. Below, I will show you the codes for implementing these three functions.
2. Function implementation
1. Registration function and login function
1.1 Code display
1.1.1 Registration function
(1) Front part
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>用户注册</title><link rel="stylesheet" type="text/css" href="../libs/bootstrap.css?1.1.11"/><style type="text/css">body{margin: 0px;padding: 0px;background-color: #CCCCCC;}.panel{width: 380px;height: 350px;position: absolute;left: 50%;margin-left: -190px;top: 50%;margin-top: -175px;}.form-horizontal{padding: 10px 20px;}.btns{display: flex;justify-content: center;}</style></head> <body><div class="panel panel-primary"><div class="panel-heading"><div class="panel-title">用户注册</div></div><div class="panel-body"><form class="form-horizontal"><div class="form-group"><label>用户名</label><input type="text" class="form-control" name="userName"/></div><div class="form-group"><label>密码</label><input type="password" class="form-control" name="pwd" /></div><div class="form-group"><label>确认密码</label><input type="password" class="form-control" name="rePwd" /></div><div class="form-group btns"><input type="button" class="btn btn-primary" value="确定注册" id="submit"/> <a type="button" class="btn btn-success" href="login.php"/>返回登录</a></div></form></div></div></body><script src="../libs/jquery-3.1.1.js?1.1.11"></script><script type="text/javascript">$(function(){ $("#submit").on("click",function(){var str = $("form").serialize(); console.log(str); $.post("doReg.php",{"formData":str},function(data){if(data=="true"){ alert("注册成功!即将跳转登陆页!"); location = "login.php"; }else{ alert("注册失败!因为啥我不知道!"); } }); }); });</script></html>
(2)Backend part
<?phpheader("Content-Type:text/html;charset=utf-8"); $str = $_POST["formData"]."[;]"; $num = file_put_contents("user.txt", $str,FILE_APPEND); if($num>0){echo "true"; }else{echo "false"; }
(3) User data storage file
userName=123&pwd=123&rePwd=123[;]// 这其实是一个普通的txt文件,就是后台部分的user.txt
1.1.2 Login function
(1) Front-end part
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>用户登录</title><link rel="stylesheet" type="text/css" href="../libs/bootstrap.css?1.1.11"/><style type="text/css">body{margin: 0px;padding: 0px;background-color: #CCCCCC;}.panel{width: 380px;height: 280px;position: absolute;left: 50%;margin-left: -190px;top: 50%;margin-top: -140px;}.form-horizontal{padding: 10px 20px;}.btns{display: flex;justify-content: center;}</style></head> <body><div class="panel panel-primary"><div class="panel-heading"><div class="panel-title">用户登录</div></div><div class="panel-body"><form class="form-horizontal"><div class="form-group"><label>用户名</label><input type="text" class="form-control" name="userName"/></div><div class="form-group"><label>密码</label><input type="password" class="form-control" name="pwd"/></div><div class="form-group btns"><input type="button" class="btn btn-primary" value="登录系统" id="submit"/> <a type="button" class="btn btn-success" href="reg.php"/>注册账号</a></div></form></div></div></body><script src="../libs/jquery-3.1.1.js?1.1.11"></script><script type="text/javascript">$(function(){ $("#submit").on("click",function(){var str = $("form").serialize(); console.log(str); $.post("doLogin.php",{"formData":str},function(data){if(data=="true"){ location = "index.php?name="+$("input[name='userName']").val(); }else{ alert("用户名或密码错误!!!"); } }); }); });</script></html>
(2)Backend part
<?phpheader("Content-Type:text/html;charset=utf-8"); $str = $_POST["formData"]; list($userName) = explode("&", $str);list(,$pwd) = explode("&", $str); $users = file_get_contents("user.txt"); $userArr = explode("[;]", $users); foreach ($userArr as $user) {list($realName) = explode("&", $user);list(,$realPwd) = explode("&", $user);if($userName==$realName&&$pwd==$realPwd){echo "true";die(); } } echo "false";
1.2 Function details
Implementation of user registration and login functions There are three main dependencies, namely, ajax transmits data to the background and accepts the results, the php background processes the data sent by ajax and feeds back the results, and receives and stores user data (this can actually be turned into the background processing part).
1.2.1 Front-end details
The main task of the front-end part is to receive information from users and transmit it to the background. The implementation of this part of the task mainly relies on two lines of code.
First, let’s take a look at how the ajax request is implemented. The implementation of this part of the function mainly relies on two lines of code.
The first line of code is var str = $("form").serialize(); The function of this line is to sequence the data submitted in the form into a string, the specific implementation is as shown below
The submitted data in the form is serialized so that the background can better parse this part.
The other key line of code is the main part of the ajax request. This part is mainly difficult to understand and is the accepted data parameters . The data parameter is a piece of information that the background feeds back to the front desk after the corresponding background processing of the ajax request is completed, such as true returned after successful registration and false returned after failure.
1.2.2 Backend details
The key to the background processing of data transmitted from the front end lies in how to obtain and parse the data transmitted. In this part, PHP provides us with three lines of code to implement.
The first line of code: $str = $_POST["formData"]; Get the front-end transmission through the super global array $_POST The serialized string solves the data acquisition part.
The second line of code: file_put_contents("user.txt", $str,FILE_APPEND); PHP provides us with file_putt_contents(), so that we can The data we obtain is stored in a file for long-term retention.
The third line of code: file_get_contents("user.txt"); This is the data extraction method provided by PHP corresponding to file_putt_contents().
Relying on the above three lines of code, coupled with our processing of data analysis, we can easily implement the entire function in the background.
2. Message function
2.1 Code display
(1) Front-end part
<!DOCTYPE html><html><head><meta charset="UTF-8"><title></title><style type="text/css">#note{width: 400px;height:100px;}</style></head><body><div id="div1"></div><textarea name="note" id="note"></textarea><br /><input type="button" id="submit" value="留言" /><h1>留言内容</h1><hr><div id="liuyanban"></div></body><script src="../libs/jquery-3.1.1.js?1.1.11"></script><script>$(function(){ getData(); var userName = '<?php echo isset($_GET["name"])?$_GET["name"]:"null"; ?>';if(userName=="null"){ location = "login.php"; } $("#div1").html("欢迎您,<span style='color:red;'>"+userName+"</span>"); $("#submit").on("click",function(){var noteVal = $("#note").val();if(noteVal==""){ alert("留言内容不能为空,请核对!");return; }var time = getTime();var note = {"userName":userName,"time":time,"noteVal":noteVal } $.post("doAdd.php",note,function(data){if(data=="true"){ alert("留言内容提交成功!"); location.reload(true); }else{ alert("留言失败!原因不明!"); } }); }); }); function getData(){ $.post("doShowNote.php",function(data){var arr = data.split("[;]"); arr.pop(); console.log(arr);for (var i=0;i< arr.length;i++) {var thisNote = $.parseJSON(arr[i]);var div = "<br/><div id='div"+i+"'>用户名:"+thisNote.userName+" 发布时间:"+thisNote.time+"<br/><br/> 留言内容:"+thisNote.noteVal+"</div><br/><hr>"$("#liuyanban").prepend(div); } }) } function getTime(){var today = new Date();var year = today.getFullYear();var month = today.getMonth();var date1 = today.getDate();var hours = today.getHours();var minutes = today.getMinutes()<10?"0"+today.getMinutes():today.getMinutes();var seconds = today.getSeconds()<10?"0"+today.getSeconds():today.getSeconds();var dateTime = year+"年"+(month+1)+"月"+date1+"日"+hours+":"+minutes+":"+seconds; return dateTime; }</script></html>
(2)Backend part
// 笔记的添加<?phpheader("Content-Type:text/html;charset=utf-8"); $userName = $_POST["userName"];$time = $_POST["time"];$noteVal = $_POST["noteVal"]; $arr = ["userName"=>$userName,"time"=>$time,"noteVal"=>$noteVal]; $str = json_encode($arr); $num = file_put_contents("note.txt", $str."[;]",FILE_APPEND); if($num>0){echo "true"; }else{echo "false"; }
// 笔记的展示<?phpheader("Content-Type:text/html;charset=utf-8");echo file_get_contents("note.txt");
(3)Message data storage file
// 这也是一个用于存储留言内容等各种信息的TXT文件{"userName":"123","time":"2017\u5e746\u670818\u65e514:01:12","noteVal":"123123"}[;]{"userName":"123","time":"2017\u5e746\u670818\u65e514:01:28","noteVal":"\u54c8\u54c8\u54c8\uff0c\u6211\u662f\u5c0fK\uff0c\u6211\u4e3a\u81ea\u5df1\u4ee3\u8a00\u3002"}[;]
2.2 Function details
2.1.1 Front-end part
The function of the front-end part is the same as the login and registration function, except that it adds the current date according to the requirements. , user name data, message board style acquisition.
2.1.2 Backend part
The backend part is actually the same routine as the backend implementation of login and registration, but it is one step more than the two. json_encode($arr); This is the method provided by PHP to convert arrays into JSON object format, which makes it easier for us to leave messages on the front end. Data feedback acquisition.
The above is the small function demo that this K brings to you for the first time this week. I hope it can help you. If there are any mistakes, please correct me. Thank you for your support!
The above is the detailed content of An example sharing of front-end and back-end interaction. 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



The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

The word demo is no longer unfamiliar to friends who like to sing, but many users who have never been exposed to it are curious about what demo means. Now let’s take a look at the meaning of the demo brought by the editor. What does demo mean? Answer: Demo tape. 1. The pronunciation of demo is ['deməʊ] in English and ['demoʊ] in America. 2. Demo is the abbreviation of "demonstration", which generally refers to the preliminary effect of listening to a song before it is officially recorded. 3. Demo is used as a noun to refer to sample tapes and sample records. The meaning of verb is trial (especially software), demonstration and demonstration;

Are you worried about WordPress backend garbled code? Try these solutions, specific code examples are required. With the widespread application of WordPress in website construction, many users may encounter the problem of garbled code in the WordPress backend. This kind of problem will cause the background management interface to display garbled characters, causing great trouble to users. This article will introduce some common solutions to help users solve the trouble of garbled characters in the WordPress backend. Modify the wp-config.php file and open wp-config.

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

As a C# developer, our development work usually includes front-end and back-end development. As technology develops and the complexity of projects increases, the collaborative development of front-end and back-end has become more and more important and complex. This article will share some front-end and back-end collaborative development techniques to help C# developers complete development work more efficiently. After determining the interface specifications, collaborative development of the front-end and back-end is inseparable from the interaction of API interfaces. To ensure the smooth progress of front-end and back-end collaborative development, the most important thing is to define good interface specifications. Interface specification involves the name of the interface

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces
