ReactJS +jQuery+Node后台取数据

来源:互联网 发布:短信验证码生成算法 编辑:程序博客网 时间:2024/06/06 11:49

这个例子结合react和ajax技术,从后台取图片,然后进行交互。为了模拟真实环境,我用node建了一个简易的后台服务。这里使用的是node5.3版本。在chrome浏览器下测试通过。

首先看项目结构:
这里写图片描述

views里html静态文件,public里是js,css,images资源。app-express.js是启动脚本,是用node express创建的一个后台服务。

先不管后台,奉上/view/index.html的完整代码:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title>    <style>* {    padding:0;    margin:0;}html{    font:14px normal Arial, sans-serif;    color:#626771;    background-color:#fff;}body{    padding:20px;    text-align: center;}h1{    font-size: 18px;    margin-bottom: 30px;    padding-top: 20px;}div.picture{    display: inline-block;    margin: 5px;    cursor:pointer;    position: relative;}div.picture.favorite:after{    content: '❤';    position: absolute;    font-size: 80px;    line-height: 200px;    color: #FF224D;    width: 100%;    text-align: center;    left: 0;    text-shadow: 0 1px 1px rgba(255, 255, 255, 0.5);    font-weight: bold;}.pictures, .favorites{    white-space: nowrap;    overflow-y: auto;    margin-bottom: 20px;    height: 230px;    background-color: #F3F3F3;}.pictures p, .favorites p {    padding-top: 100px;    font-size: 13px;}    </style>    <script src="js/jquery-1.11.3.min.js"></script>    <script src="js/react.min.js"></script>    <script src="js/react-dom.min.js"></script>    <script src="js/browser.min.js"></script></head><body>    <script  type="text/babel">    var Picture = React.createClass({        clickHandler: function(){               this.props.onClick(this.props.pid);        },        render: function(){            var cls = 'picture ' + (this.props.favorite ? 'favorite' : '');            return (                <div className={cls} onClick={this.clickHandler}>                    <img src={this.props.src} width="200" title={this.props.title} />                </div>            );        }    });    var PictureList = React.createClass({        getInitialState: function(){                    // 通过AJAX取图片列表,用户点击图片加入收藏                    return { pictures: [], favorites: [] };        },        componentDidMount: function(){             // 组件加载完成后发送一个AJAX请求            var self = this;            // 从node服务中获取图片列表            var url = '/pictures';            $.getJSON(url, function(result){                if(!result || !result.pictures || !result.pictures.length){                    return;                }                var pictures = result.pictures.map(function(p){                    return {                         pid: p.pid,                         src: p.src,                         title: p.title ? p.title : '',                         favorite: false                     };                });                // 更新组件状态,这会触发一次render,此处只更新Pictures数组,不会删除favorites数组                self.setState({ pictures: pictures });            });        },        pictureClick: function(pid){            // id变量即点击图片的ID,从pictures数组里找出它并把它加到favorites数组中去            var favorites = this.state.favorites,                pictures = this.state.pictures;            for(var i = 0; i < pictures.length; i++){                // 从pictures数组里找出  pid                if(pictures[i].pid == pid) {                      if(pictures[i].favorite){                        return this.favoriteClick(pid);                    }                    // 把它加到favorites数组中,标记它的favoritetrue                    favorites.push(pictures[i]);                    pictures[i].favorite = true;                    break;                }            }            // 更新状态,重新触发一次render            this.setState({pictures: pictures, favorites: favorites});        },        favoriteClick: function(pid){            // 在favorites 数组中找出这个picture并移除. 然后在pictures数组中找出picture并标记non-favorite            var favorites = this.state.favorites,                pictures = this.state.pictures;            for(var i = 0; i < favorites.length; i++){                if(favorites[i].pid == pid) break;            }            // 移除            favorites.splice(i, 1);            for(i = 0; i < pictures.length; i++){                if(pictures[i].pid == pid) {                    pictures[i].favorite = false;                    break;                }            }            // 更新状态并触发render            this.setState({pictures: pictures, favorites: favorites});        },        render: function() {            var self = this;            var pictures = this.state.pictures.map(function(p){                return <Picture pid={p.pid} src={p.src} title={p.title} favorite={p.favorite} onClick={self.pictureClick} />            });            if(!pictures.length){                pictures = <p>Loading images..</p>;            }            var favorites = this.state.favorites.map(function(p){                return <Picture pid={p.pid} src={p.src} title={p.title} favorite={true} onClick={self.favoriteClick} />            });            if(!favorites.length){                favorites = <p>Click an image to mark it as a favorite.</p>;            }            return (                <div>                    <h1>热门图片</h1>                    <div className="pictures"> {pictures} </div>                    <h1>我的收藏</h1>                    <div className="favorites"> {favorites} </div>                </div>            );        }    });    // Render  PictureList 组件并加到body中    React.render(        <PictureList apiKey="642176ece1e7445e99244cec26f4de1f" />,        document.body    );    </script></body></html>

图片和脚本资源准备(请自行准备)
这里写图片描述

这里写图片描述

用的全是windows自带的图片,哈哈。

脚本:
这里写图片描述

多了个jquery,我们主要使用jquery的ajax,不喜欢用框架的自已去写吧。

OK,现在打开页面还不能运行,把app-express.js的脚本加上:

var express = require('express');var path = require('path');var bodyParser = require('body-parser');var http = require('http');var fs=require('fs');var mime=require('mime');var app = express();app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));app.set('views', path.join(__dirname, 'views'));app.use(express.static(path.join(__dirname, 'public')));app.get('/', function(req, res) {    var fname="views/index.html";    fs.readFile(fname,function(err,buf){        res.writeHead(200,{'Content-Type':mime.lookup(fname),'Content-Length':buf.length});        res.end(buf);    });});app.get('/pictures', function(req, res) {    res.writeHead(200,{'Content-Type':'application/json'});    res.end(JSON.stringify({        pictures: [{             pid:"1",             src:"images/Chrysanthemum.jpg",             title:"Chrysanthemum",             favorite: false          },{             pid:"2",                        src:"images/Desert.jpg",             title:"Desert",             favorite: false          },{             pid:"3",                        src:"images/Hydrangeas.jpg",             title:"Hydrangeas",             favorite: false          },{             pid:"4",                        src:"images/Jellyfish.jpg",             title:"Jellyfish",             favorite: false          },{             pid:"5",                        src:"images/Koala.jpg",             title:"Koala",             favorite: false          },{             pid:"6",                        src:"images/Lighthouse.jpg",             title:"Lighthouse",             favorite: false          },{             pid:"7",                        src:"images/Penguins.jpg",             title:"Penguins",             favorite: false          },{             pid:"8",                        src:"images/Tulips.jpg",             title:"Tulips",             favorite: false          }]     }));});var server = http.createServer(app);server.listen('8100');

需要安装各种插件,通过npm自行安装哦。比如npm install body-parser

好了,源码都完成了,启动node app-express.js
在浏览器里输入http://localhost:8100/
这里写图片描述

全套源码下载地址(需要点资源分,攒点分下资源,望谅解^_^):
ReactJS+jQuery+Node实例源码下载

0 0
原创粉丝点击