Home > Web Front-end > JS Tutorial > Using Ajax to implement registration and avatar upload functions

Using Ajax to implement registration and avatar upload functions

php中世界最好的语言
Release: 2018-04-02 15:50:29
Original
2731 people have browsed it

This time I will bring you the use of Ajax to implement the registration and avatar upload functions. What are the precautions for Ajax to implement the registration and avatar upload functions. The following is a practical case, let's take a look.

After the first contact with ajax, we did a CRM training project. Most groups have registered users, but they all ignored one function, that is, registrations for many websites can be uploaded. For avatars, here I made a small CRM that selects pictures from the existing avatar array and uploads them as avatars (of course, I haven’t made one that can be uploaded and cropped from local photos, but I will as long as I have time. Research, I believe it won’t take too long).

1. First write a registration page and css style. I named it regist.html, and the css file is named regist.css. I omit the specific code here. See the effect in the picture above. Bar: (The page is a bit ugly, don’t mind)

There is also an information.html page used to display the added records. At this time, there is only the header:

2. Write the creation connection pool module (dbutil.js), which is the js file for establishing the link. What I built here is the users_infor table, and the database used is test.

var mysql = require('mysql');
var pool = mysql.createPool({
host : 'localhost',
user : 'root',
password : 'lovo',
database:"test",
port:3306
});
exports.pool=pool;
Copy after login

3. Write a module to connect to the database and process (add, delete, modify, and query) user data (Userdao.js). All functions that operate the database are named getAllUser:

var db = require("../DBUtil/dbutil.js");
//var conn = db.conn;
var mypool =db.pool;
function getAllUser(sql,arg,fun){
mypool.getConnection(function(err,conn){
conn.query(sql,arg,fun);
conn.end();
})
}
exports.getAllUser=getAllUser;
Copy after login

4. Write the module to operate the database, that is, add, delete, modify, and query the data table (Userservice.js):

var dao = require("../dao/UserDao.js");
Copy after login

Define the registration function, that is, go to the data table user_infor The function of adding new records

exports.regist = function(req,res){
var arg;
if (req.method == "get" || req.method == "GET") {
arg = [req.query.username, req.query.pwd, req.query.pics];
} else {
arg = [req.body.username, req.body.pwd, req.body.pics];
}
var sql = "insert into user_infor(u_name,u_pwd,u_pics) values(?,?,?)"
dao.getAllUser(sql, arg, function (err, result) {
if (err) {
console.log(err);
} else {
if (result.affectedRows>0){
res.sendfile("./static/html/information.html")
} else {
res.sendfile("./static/html/regist.html")
}
}
})
}
Copy after login

Define the function that displays all the records of the information.html page, that is, the function that queries all the contents of the user_infor table

exports.listAll=function(req,res){
var sql = " select * from user_infor ";
dao.getAllUser(sql,function (err, result, fields) {
if (err){
console.log(err);
} else {
if (result.length>0){
res.json(result);console.log(result)
} else {
res.send("failed");
}
}
})
}
Copy after login

5. Of course, don’t forget to introduce the 2 modules express and mysql, create a new folder node_module and include these two modules in it.

6. Then, write a main js file (main.js), which is the js that interacts with the user:

var http = require("http");
var express = require("express");
var userser = require("./route/UserService.js");
var url= require("url");
var app = express();
app.use(express.cookieParser());
app.use(express.session({
secret:"123456",
name:"userLogin",
cookie:{maxAge:9999999}
}))
app.set("port",8888);
app.use(express.static(dirname+"/static"));
app.use(express.methodOverride());
app.use(express.bodyParser());
app.post("/regist",userser.regist);
app.post("/list",userser.listAll);
http.createServer(app).listen(app.get("port"),function(){
console.log("服务启动成功!监听"+app.get("port")+"端口");
})
Copy after login

7. The following js file is for register and information, respectively:

--------------------------------regist page selection avatar function -------------------------------------------------- ----------

function xuanze() {
var pics=document.getElementById("pics");
var picsp = document.getElementById("login_pics");
picsp.style.display = 'block';
var img=document.getElementsByTagName("img");
var picarrs=["../img/user1.jpg",
"../img/user2.jpg",
"../img/user3.jpg",
"../img/user4.jpg",
"../img/user5.jpg",
"../img/user6.jpg",
"../img/user7.jpg",
"../img/user8.jpg",
"../img/user9.jpg",
"../img/user10.jpg",
"../img/user11.jpg",
"../img/user12.jpg",
"../img/user13.jpg",
"../img/user14.jpg",
"../img/user15.jpg",
"../img/user16.jpg",
"../img/user17.jpg",
"../img/user18.jpg",
"../img/user19.jpg",
"../img/user20.jpg",
"../img/user21.jpg",
"../img/user22.jpg",
"../img/user23.jpg",
"../img/user24.jpg"];
for(var i=0;i<picarrs.length;i++){
img[i].src=picarrs[i];
}
for(var j=0;j<img.length;j++){
img[j].onclick=function(e){
var target= e.target|| e.srcElement;
var imgroute=target.src;//此处若弹出imgroute,可以看到完全路径是http:localhost:8888/img/users20.jpg
pics.value=".."+imgroute.substr(21);/*此处要截取后面的部分才是图片的路径,前面的http:localhost:8888要省去,不是我们需要的路径,若不截取将无法识别*/
}
}
}
Copy after login

-----------------------The information page displays all recorded functions, window one Load to display all------------------------------------------------- --

window.onload=function(){
var xmlhttpReq;
if (window.XMLHttpRequest)
xmlhttpReq=new XMLHttpRequest();
else
xmlhttpReq=new ActiveXObject("Microsoft.XMLHTTP");
var url="http://localhost:8888/list";
//初始化信息
xmlhttpReq.open("post",url,true);
//添加请求头
xmlhttpReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttpReq.send(null);
xmlhttpReq.onreadystatechange = function(){
if (xmlhttpReq.readyState==4 && xmlhttpReq.status==200) {
if (xmlhttpReq.responseText != "failed"){
var userinfor = document.getElementById("userinfor");
var users = eval("(" + xmlhttpReq.responseText + ")");
for (var i = 0; i < users.length; i++){
var newRow = userinfor.insertRow();
newRow.style.height = "100px";
newRow.style.backgroundColor = "skyblue";
newRow.insertCell(newRow.cells.length).innerHTML =users[i].u_name;
newRow.insertCell(newRow.cells.length).innerHTML =users[i].u_pwd;
newRow.insertCell(newRow.cells.length).innerHTML ="<img src=&#39;"+users[i].u_pics+"&#39;>";//此处要在这个单元格里插入img元素,将提交传过来的路径指定为此img的
Copy after login

src, if there is no such img element, the path displayed here is still the path, and no picture will appear.

newRow.insertCell(newRow.cells.length).innerHTML ="<input type=&#39;button&#39; id=&#39;del&#39; id=&#39;" + users[i].u_id + "&#39; value=&#39;删除信息&#39; onclick=&#39;shanchu(this)&#39;/>";
}
} else if (xmlhttpReq.responseText == "failed") {
alert("添加新用户失败");
}
}
}
}
Copy after login

8. The most important point is that when creating a new user_infor table in the database, specify the user_pics field to specify the path where the pictures are stored:

USE test;
DROP TABLE IF EXISTS user_infor;
CREATE TABLE user_infor(
u_id INT PRIMARY KEY AUTO_INCREMENT,
u_name CHAR(20) NOT NULL,
u_pwd CHAR(20) NOT NULL,
u_pics CHAR(100) NOT NULL
)
INSERT INTO user_infor(u_name,u_pwd,u_pics) VALUES
('xiaoming','111111','../img/user12.jpg'),
('xiaofang','222222','../img/user13.jpg'),
('xiaozhou','333333','../img/user14.jpg')
Copy after login

The file storage relationship of the entire project is as follows:

Open the database with SQLyog, run main.js, open register.html in the browser, start registration and select the avatar:

After clicking on an avatar and returning, the path to the image will be generated in the text box of the avatar, as follows:

Click submit to complete the registration. The page will jump to the information page. After several successful registrations, the page will appear as follows:

Believe it or not 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 use Ajax and $.ajax

Detailed explanation of the steps of using ajax to implement paging technology (With code)

The above is the detailed content of Using Ajax to implement registration and avatar upload functions. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template