Ajax implements the upload function after registering and selecting the Avatar, and ajax Avatar

Source: Internet
Author: User
Tags sendfile

Ajax implements the upload function after registering and selecting the Avatar, and ajax Avatar

After getting started with ajax for the first time, we had a crm Training Project. Most groups had registered users, but ignored a function, that is, you can upload portraits for registration on many websites. Here, I have created a small crm system that selects images to upload as portraits in an existing Avatar array (of course, I can upload and crop a local photo, but I will study it as long as I have time. I believe it will not be too long ).

1. First, write a registration page named "regist.html" and the CSS file named "regist.css". Here I will omit the specific code to see the effect: (the page is ugly, don't mind)

There is also a information.html page that displays the last record. At this time, only the header:

2. write out the create Connection Pool Module (dbutil. js), that is, the js file that creates the link. Here I create 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. The write module is used to connect to the database and process (add, delete, modify, and query) user data (Userdao. js). In this module, all database operation functions 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;

4. Write down the database module, that is, adding, deleting, modifying, and querying data tables (Userservice. js ):

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

Defines the registration function, that is, the function that adds a new record 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 records on the information.html page, that is, the function that queries all 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, do not forget to introduce two modules express and mysql, create a folder node_module, and include these two modules in it.

6. Then, write a major js file (main. js), that 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 ("service started successfully! Listener "+ app. get (" port ") +" port ");})

7. The following js files for regist and information are as follows:

------------------------------ The regist page selects the Avatar function ------------------------------------------------------------

Function xuanze () {var pics = document. getElementById ("pics"); var picsdiv = document. getElementById ("login_pics"); picsdiv. 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/user‑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 

----------------------- The information page displays the functions of all records. When a window is loaded, all functions are displayed ------------------------------------------------

Window. onload = function () {var xmlhttpReq; if (window. XMLHttpRequest) xmlhttpReq = new XMLHttpRequest (); elsexmlhttpReq = new ActiveXObject ("Microsoft. XMLHTTP "); var url =" http: // localhost: 8888/list "; // initialization information xmlhttpReq. open ("post", url, true); // Add the request header xmlhttpReq. setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); xmlhttpReq. send (null); xmlhttpReq. onreadystatechange = function () {if (xmlhttpReq. ready State = 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 = "

Src. If this img element is not present, the path is displayed here, and no image is displayed.

NewRow. insertCell (newRow. cells. length ). innerHTML = "<input type = 'button 'id = 'del 'id = '" + users [I]. u_id + "'value = 'delete information' onclick = 'shanchu (this) '/>" ;}} else if (xmlhttpReq. responseText = "failed") {alert ("failed to add a new user ");}}}}

8. The most important thing is to specify the user_pics field when creating a user_infor table in the database to specify the path for storing images:

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 relationships of the entire project are as follows:

Use sqlyogto open the data warehouse, run main.js, open regist.html in the browser, start registration, and select the Avatar:

After clicking an avatar and returning it, the text box of the Avatar generates the image path, as shown below:

Click Submit to complete the registration. The page jumps to the information page. After successful registration, the page is displayed as follows:

The Avatar can also be uploaded, because the style written in a rush is not beautiful, please forgive me! If you have any questions, please leave a message and the editor will reply to you in time. Thank you very much for your support for the help House website!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.