Home  >  Article  >  Backend Development  >  An example sharing of front-end and back-end interaction

An example sharing of front-end and back-end interaction

零下一度
零下一度Original
2017-06-26 14:44:223451browse

 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=&#39;color:red;&#39;>"+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=&#39;div"+i+"&#39;>用户名:"+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!

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