


Ajax implements the function of registering and selecting an avatar and then uploading it
This article mainly introduces the Ajax function of registering and selecting an avatar and then uploading it. It is very good and has reference value. Friends in need can refer to it
After the first contact with ajax, we made a crm For training projects, most groups have registered users, but they all ignore one feature, that is, registration on many websites allows you to upload avatars. Here I made a selection from the existing avatar array. A small CRM that uploads pictures as avatars (of course, I haven't made one that can upload and crop local photos, but I will study it as long as I have time, and I believe it won't take long).
1. First write a registration page and css style. I named it regist.html, and the css file is called regist.css. I omit the specific code here. See the effect in the picture above: (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 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;
3. Write a module to connect to the database and process (add, delete, modify and query) user data (Userdao.js), which contains the same functions for operating the database Name it 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;
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");
Define the registration function, which is the function that adds new records to the data table user_infor
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") } } }) }
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"); } } }) }
5. Of course, don’t forget to introduce For the two 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")+"端口"); })
7. The following js files are for register and information, respectively:
-------------------------- ------Function to select avatar on the register page----------------------------------------- -----------------------
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要省去,不是我们需要的路径,若不截取将无法识别*/ } } }
--------- ---------------The information page displays all recorded functions, and all are displayed as soon as the window is loaded---------------------- --------------------------
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='"+users[i].u_pics+"'>";//此处要在这个单元格里插入img元素,将提交传过来的路径指定为此img的
src, if you don’t have this img element, the path displayed here is still the path, and no picture will appear.
newRow.insertCell(newRow.cells.length).innerHTML ="<input type='button' id='del' id='" + users[i].u_id + "' value='删除信息' onclick='shanchu(this)'/>"; } } else if (xmlhttpReq.responseText == "failed") { alert("添加新用户失败"); } } } }
8. And 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')
The file storage relationship of the entire project is as follows:
Open the database with SQLyog and run main.js. Open register.html in the browser, start registration and select an avatar:
Click on an avatar and return to the avatar The path to the image is generated in the text text box, as follows:
#Click submit to complete the registration. The page jumps to the information page. After several successful registrations, the page It will be displayed as follows:
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Details the differences between async:false and async:true in Ajax requests
Ajax and Mysql data interaction production message board function
Instances of ajax responding to json strings and json arrays (graphic tutorial)
The above is the detailed content of Ajax implements the function of registering and selecting an avatar and then uploading it. 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

Does Wallpaper support family sharing? Unfortunately, it cannot be supported. Still, we have solutions. For example, you can purchase with a small account or download the software and wallpapers from a large account first, and then change to the small account. Simply launching the software is perfectly fine. Can wallpaperengine be family shared? Answer: Wallpaper does not currently support the family sharing function. 1. It is understood that WallpaperEngine does not seem to be suitable for family sharing environments. 2. In order to solve this problem, it is recommended that you consider purchasing a new account; 3. Or download the required software and wallpapers in the main account first, and then switch to other accounts. 4. Just open the software with a light click and it will be fine. 5. You can view the properties on the above web page"

WallpaperEngine is a software commonly used to set desktop wallpapers. Users can search for their favorite pictures in WallpaperEngine to generate desktop wallpapers. It also supports adding pictures from the computer to WallpaperEngine to set them as computer wallpapers. Let’s take a look at how wallpaperengine sets the lock screen wallpaper. Wallpaperengine setting lock screen wallpaper tutorial 1. First enter the software, then select installed, and click "Configure Wallpaper Options". 2. After selecting the wallpaper in separate settings, you need to click OK on the lower right. 3. Then click on the settings and preview above. 4. Next

Users can download various wallpapers when using WallpaperEngine, and can also use dynamic wallpapers. Many users do not know whether there are viruses when watching videos on WallpaperEngine, but video files cannot be used as viruses. Is there any virus when watching movies on wallpaperengine? Answer: No. 1. Just video files cannot be used as viruses. 2. Just make sure to download videos from trusted sources and maintain computer security measures to avoid the risk of virus infection. 3. Application wallpapers are in apk format, and apk may carry Trojan viruses. 4. WallpaperEngine itself does not have viruses, but some application wallpapers in the creative workshop may have viruses.

When using wallpaper, users can download various wallpapers they like for use. Many users do not know which folder the wallpapers are in. The wallpapers downloaded by users are stored in the content folder. Which folder is the wallpaper in? Answer: content folder. 1. Open File Explorer. 2. Click "This PC" on the left. 3. Find the "STEAM" folder. 4. Select "steamapps". 5. Click “workshop”. 6. Find the “content” folder.

Users can change their computer wallpapers when using WallpaperEngine. Many users don't know that WallpaperEngine consumes a lot of power. Dynamic wallpapers consume a little more power than static wallpapers, but not a lot. Does wallpaperengine consume a lot of power? Answer: Not much. 1. Dynamic wallpapers consume a little more power than static wallpapers, but not a lot. 2. Turning on dynamic wallpaper will increase the computer's power consumption and take away a small amount of memory usage. 3. Users do not need to worry about the serious power consumption of dynamic wallpapers.

How to check wallpaper subscription records? Many users have made a large number of subscriptions on this software, but may not know how to query these records. In fact, you only need to operate it in the browsing function area of the software. Where are wallpaperengine subscription records? Answer: In the browsing interface. 1. Please start the computer first and enter the wallpaper software. 2. Find the Browse tab icon in the upper left corner of the application and click it. 3. In the "Browse" interface, you will see an overview of various wallpapers and feeds. 4. Enter the keywords you want to search in the search box in the upper right corner. 5. Relying on the search results, you can find the source information of the wallpaper subscription. 6. Click on the corresponding feed to enter its web page. 7. Ordering

I guess you are not familiar with the Microsoft Edge browser, but do you know how to change the font size in the Microsoft Edge browser? The following article describes how to change the font size in the Microsoft Edge browser. Let's study it together. First, find the Microsoft Edge browser and double-click it to open it. You can find the Microsoft Edge browser in the desktop shortcut, start menu or taskbar, and double-click to open it. Secondly, open the [Settings] interface to enter this browser interface, click the [...] logo in the upper left corner; double-click [Settings] to open the settings interface. Again, find and open the [Appearance] interface and scroll down with the mouse

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.
