记学校一次javaweb小测试:使用 AJAX 技术开发一个购物网站购物车功能(ajax+nodejs)

题目:

在这里插入图片描述

特别说明:因为是java web程序设计这门课,所以老师的要求不仅仅是会用ajax就完事儿,需要自己使用java来连接数据库写后台,然后前端ajax获取。
(PS:因为自己java学的一般,又一直在搞纯前端的东西。所以自己鼓捣了一下用nodejs来实现后端,前端使用ajax获取来完成这个题目)

样例

后端
sql.js

// nodejs部分
// 作用:实现连接数据库获取增加数据,开启一个web服务器

// 引入相关模块
var mysql = require('mysql')	// mySQL模块
var express = require('express') // express WEB应用框架模块
var app = express()
var util = require('util') // 常用库函数模块
var bodyParser = require('body-parser') // 解析POST请求模块
var fs = require('fs') // 文件操作模块

// 定义post请求体
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// 连接数据库相关配置
var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'goodcart'
})
connection.connect() // 开启连接

var sql = 'SELECT * FROM goods' // 定义数据库商品查询语句
var addSql = 'INSERT INTO goods(goodName) VALUES(?)' // 定义数据库商品增加语句

// get请求定向到index.html(访问本地服务器(127.0.0.1:8081)页面时访问index.html)
app.get('/', function (req, res) { 
  res.sendFile(__dirname + '/' + 'index.html')
}) 

// 获取post请求实现商品增加到数据库的功能
app.post('/addGood', urlencodedParser, function (req, res) {
  for(let i in req.body) {
    var goodName = i
  }
  res.send('添加成功')
  console.log(goodName);
  // 增
  connection.query(addSql, [goodName], function (err, result) {
    if (err) {
      console.log('INSERT ERROR - ', err.message)
      return
    }
  })
})

// 获取get请求实现查询商品
app.get('/loadGoods', function (req, res) {
  // 查
  var goods = []
  connection.query(sql, function (err, result) {
    if (err) {
      console.log('[SELECT ERROR] - ', err.message)
      returns
    }
    for (let i = 0; i < result.length; i++) {
      goods.push(result[i].goodName)
    }
    res.json({message: goods});
  })
})

// 开启端口为8081的web服务器
var server = app.listen(8081, function () {
  var host = server.address().address
  var port = server.address().port

  console.log('running at http://' + host + ':' + port)
})

前端:
index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
  <title>Test</title>
</head>
<style>
 .container {
   display: flex;
   flex-wrap: nowrap;
   justify-content: space-around;
 }
 .goods-list {
   margin: 50px auto;
   display: flex;
   flex-wrap: wrap;
   width: 500px;
   height: 300px;
   border: 1px solid black;
   opacity: 0;
 }
 .goods-list h1 {
   margin: 0 10px;
 }
 .shop-cart {
   position: absolute;
   bottom: 0;
   right: 0;
   padding: 20px 100px;
   border: 1px solid black;
 }
</style>
<script type="text/javascript">
// ajax 请求部分
	var xhr;
  var isIE=false;
  var isShopCart=false;
	function getXMLHttpRequest() {
	    if (window.XMLHttpRequest) {
	        if (navigator.userAgent.indexOf('MSIE') != -1) {
	            isIE = true;
	        }
	        return new XMLHttpRequest();
	    } else if (window.ActiveXObject) {
	        isIE = true;
	        return new ActiveXObject("Microsoft.XMLHTTP");
	    }
	}
	
	function init() {
		
		xhr = getXMLHttpRequest();
		if(xhr) {
			xhr.onreadystatechange = handleResponse;
		} else {
			alert("你的浏览器不支持ajax!推荐使用firefox或者chrome浏览器访问!");
		}
	}
	
	function addGoods(id) {
		if(xhr) {
      xhr.open("POST", "/addGood");
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.send('商品' + id);
    }
  }
  
  function loadGoods() {
		if(xhr) {
      xhr.open("GET", "/loadGoods");
      xhr.send();
    }
    console.log('获取商品')
	}
	
	function handleResponse() {
		if(xhr.readyState == 4) {
			if(xhr.status == 200 || xhr.status == 304) {
        if (isShopCart) {
          var goods = JSON.parse(xhr.responseText).message
          $(".goods-list").empty();
          for (let i = 0; i < goods.length; i++) {
            $(".goods-list").append(`<h1>${goods[i]}</h1>`)
          }
        } else {
          alert('提交成功')
        }
			}
		}
	}
</script>
<body onload="init()">
  <div class="container">
    <div class="good-content">
      <h1>商品1</h1>
      <button id="#btn1" onclick="addGoods(1)">添加</button>
    </div>
    <div class="good-content">
      <h1>商品2</h1>
      <button onclick="addGoods(2)">添加</button>
    </div>
    <div class="good-content">
      <h1>商品3</h1>
      <button onclick="addGoods(3)">添加</button>
    </div>
    <div class="good-content">
      <h1>商品4</h1>
      <button onclick="addGoods(4)">添加</button>
    </div>
    <div class="good-content">
      <h1>商品5</h1>
      <button onclick="addGoods(5)">添加</button>
    </div>
  </div>
  <div class="goods-list">
  </div>
  <div class="shop-cart">
    购物车
  </div>
</body>
<script>
  $(document).ready(function(){
    $(".shop-cart").mouseenter(function () {
      loadGoods()
      isShopCart = true;
      $(".goods-list").css("opacity", "1")
    })
    $(".shop-cart").mouseleave(function () {
      $(".goods-list").css("opacity", "0")
      isShopCart = false;
    })
  });
</script>
</html>

效果:
(点击添加)
在这里插入图片描述
(加载购物车商品)
在这里插入图片描述

因为nodejs接触不久,写的有很多不妥或者凌乱的地方,求大佬指正谢谢、

相应工程:https://download.youkuaiyun.com/download/weixin_43388844/11203612
(node环境运行,并开启数据库端口)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值