安装node.js
直接官网下载,默认安装就行。
安装express
在当前工程文件目录下
express -e
npm install
安装mysql
npm install mysql --save-dev
express 安装后
app.js 配置文件
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use('/news', index); //监听发往news的请求的时候,用index路由
app.use('/users', users);
routes ==> index.js
var express = require('express');
var router = express.Router();
var mysql = require('mysql')
router.get('/', function(req, res, next) {
var newstype=req.query.newstype; //查询条件
//mysql数据库连接
var connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'root',
database: 'xynews'
});
connection.connect();
//sql语句
connection.query('SELECT * FROM `baidunews2` where `newstype` = ?',[newstype],function(err, rows, fields) {
console.log(rows);
//返回json对象结果
res.json(rows);
})
});
module.exports = router;
js ==》news.js
$(document).ready(function() {
refreshNews("1");
$(".typeon span").on("click",function(){
var index=$(this).index();
refreshNews(index+1)
});
});
function refreshNews(type) {
var $lists = $(".article ul");
$lists.empty();
$.ajax({
url: '/news',
type: 'get',
datatype: 'json',
data: { newstype: type },
success:function(data) {
console.log(data);
for (var i = 0; i <= data.length - 1; i++) {
var $list = $('<li>' + data[i].news_text + '</li>').appendTo($lists);
}
}
})
}
html==》index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css" media="screen">
.typeon{
width: 600px;
}
span {
display: inline-block;
width: 200px;
height: 100px;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<div class="typeon">
<span>分类1</span><span>分类2</span><span>分类3</span>
</div>
<div class="article">
<ul></ul>
</div>
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/news.js"></script>
</body>
</html>
简单的实现了,数据的查询与显示!!