Node服务端+React前端+ajax实现方式

Node作为服务端配置过程如下:

1) 命令行进入rest-api-demo目录,执行下面的命令。

$ npm install -S json-server

(2) 在项目根目录下,新建一个 JSON 文件db.json,文件内容为:

{
  "customers": [
    {
      "customerName": "user",
      "contactName": "张三",
      "phone": "136",
      "id": 1
    }
  ],
  "profile": {
    "name": "typicode"
  }
}

(3) 打开package.json,在scripts字段添加一行。

"scripts": {
  "server": "json-server db.json",
  "test": "..."
},

(4) 命令行下执行下面的命令,启动服务。

$ npm run server
这样Node服务端就配置完成了,目前只有一个对象Customer,支持REST API。

前端HTML代码如下:
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="bootstrap\css\bootstrap.min.css">
    <script src="jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="bootstrap\js\bootstrap.min.js" type="text/javascript"></script>
    <script src="jquery-1.10.2.min.js" type="text/javascript"></script>
</head>
<body>
    <div id="app" style="width:600px;height:480px;margin:50px auto;">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>
                        CustomerId
                    </th>
                    <th>
                        CompanyName
                    </th>
                    <th>
                        ContactName
                    </th>
                    <th>
                        Phone
                    </th>
                    <th>Delete</th>
                </tr>
            </thead>
            <tbody id="tbody"></tbody>
        </table>
        <div>
            <button type="button" class="btn btn-primary" onclick="btnAdd()">Create</button>
        </div>
        <div class="dialog" id="dialog" style="display:none;width:400px;height:300px;">
            <form class="form-horizontal">
                <fieldset>
                    <div id="legend" class="">
                        <legend class="">新建</legend>
                    </div>
                    <div class="control-group">
                        <label class="control-label" for="input01">CustomerName</label>
                        <div class="controls">
                            <input type="text" placeholder="" class="input-xlarge" id="inputCustomerName">
                            <p class="help-block"></p>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label" for="input01">ContactName</label>
                        <div class="controls">
                            <input type="text" placeholder="" class="input-xlarge" id="inputContactName">
                            <p class="help-block"></p>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label" for="input01">Phone</label>
                        <div class="controls">
                            <input type="text" placeholder="" class="input-xlarge" id="inputPhone">
                            <p class="help-block"></p>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label"></label>
                        <div class="controls">
                            <button class="btn btn-success" onclick="addCustomer()">确定</button>
                        </div>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>

    <div>
        <button onclick="timedGetText()">GET</button>
    </div>
    <div id="example">
    </div>
    <script type="text/javascript">
        initCustomer();
        function btnAdd() {
            $("#dialog").show();
        }

        function addCustomer() {
            var customerObj = {};
            customerObj.customerName = $("#inputCustomerName").val();
            customerObj.contactName = $("#inputContactName").val();
            customerObj.phone = $("#inputPhone").val();

            $.ajax({
                url: "http://127.0.0.1:3000/customers",    //请求的url地址
                dataType: "json",   //返回格式为json
                data: customerObj,
                async: true, //请求是否异步,默认为异步,这也是ajax重要特性
                type: "POST",   //请求方式
                beforeSend: function () {
                    //请求前的处理
                },
                success: function (data) {
                    //请求成功时处理
                    var htmlStr = '';
                    for (var i = 0; i < data.length; i++) {
                        htmlStr += "<tr><td><span><a href='javascript:void(0)'>" + data[i].id + "</a></span></td><td><span>" + data[i].customerName + "</span></td><td><span>" + data[i].contactName + "</span></td><td><span>" + data[i].phone + "</span></td><td><button type='button' class='btn btn-danger'>delete</button></td></tr>";
                    }
                    document.getElementById('tbody').innerHTML = htmlStr;
                },
                complete: function () {
                    //请求完成的处理
                },
                error: function () {
                    //请求出错处理
                }
            });
        }

        function deleteCustomer(id) {
            $.ajax({
                url: "http://127.0.0.1:3000/customers/"+id,    //请求的url地址
                dataType: "json",   //返回格式为json
                async: true, //请求是否异步,默认为异步,这也是ajax重要特性
                type: "DELETE",   //请求方式
                beforeSend: function () {
                    //请求前的处理
                },
                success: function (data) {
                    initCustomer();
                    alert("删除成功!");
                },
                complete: function () {
                    //请求完成的处理
                },
                error: function () {
                    //请求出错处理
                }
            });
        }

        function initCustomer() {
            $.ajax({
                url: "http://127.0.0.1:3000/customers",    //请求的url地址
                dataType: "json",   //返回格式为json
                async: true, //请求是否异步,默认为异步,这也是ajax重要特性
                type: "GET",   //请求方式
                beforeSend: function () {
                    //请求前的处理
                },
                success: function (data) {
                    //请求成功时处理
                    var htmlStr = '';
                    for (var i = 0; i < data.length; i++) {
                        htmlStr += "<tr><td><span><a href='javascript:void(0)'>" + data[i].id + "</a></span></td><td><span>" + data[i].customerName + "</span></td><td><span>" + data[i].contactName + "</span></td><td><span>" + data[i].phone + "</span></td><td><button type='button' class='btn btn-danger' onclick='deleteCustomer(" + data[i].id + ")'>delete</button></td></tr>";
                    }
                    document.getElementById('tbody').innerHTML = htmlStr;
                },
                complete: function () {
                    //请求完成的处理
                },
                error: function () {
                    //请求出错处理
                }
            });
        }
    </script>
</body>
</html>
HTML+JS

前端使用React,后端Node的实现方式:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="bootstrap\css\bootstrap.min.css">
    <script src="jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="bootstrap\js\bootstrap.min.js" type="text/javascript"></script>
    <script src="jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="react\react.js" type="text/javascript"></script>
    <script src="react\react-dom.js" type="text/javascript"></script>
    <script src="react\babel.min.js" type="text/javascript"></script>
</head>
<body>
    <div id="app" style="width:600px;height:480px;margin:50px auto;">
        <div id="divTable">
        </div>
        <div>
            <button type="button" class="btn btn-primary" onClick="btnAdd()">Create</button>
        </div>
        <div class="dialog" id="dialog" style="display:none;width:400px;height:300px;">
            <form class="form-horizontal">
                <fieldset>
                    <div id="legend" class="">
                        <legend class="">新建</legend>
                    </div>
                    <div class="control-group">
                        <label class="control-label" for="input01">CustomerName</label>
                        <div class="controls">
                            <input type="text" placeholder="" class="input-xlarge" id="inputCustomerName">
                            <p class="help-block"></p>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label" for="input01">ContactName</label>
                        <div class="controls">
                            <input type="text" placeholder="" class="input-xlarge" id="inputContactName">
                            <p class="help-block"></p>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label" for="input01">Phone</label>
                        <div class="controls">
                            <input type="text" placeholder="" class="input-xlarge" id="inputPhone">
                            <p class="help-block"></p>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label"></label>
                        <div class="controls">
                            <button class="btn btn-success" onClick="addCustomer()">确定</button>
                        </div>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>
    <div id="example"></div>
    <script type="text/babel">
        class MyTitle extends React.Component {
            constructor(...args) {
                super(...args);
                this.state = {
                    loading: true,
                    data:null
                };
            }

        componentDidMount() {
            $.ajax({
                url: "http://127.0.0.1:3000/customers",
                //请求的url地址
                dataType: "json",
                //返回格式为json
                async: true,
                //请求是否异步,默认为异步,这也是ajax重要特性
                type: "GET",
                //请求方式
                beforeSend: function() {
                    //请求前的处理
                },
                success: function(datas) {
                    this.setState({
                        loading: false,
                        data: datas
                    });
                }.bind(this),
                complete: function() {
                    //请求完成的处理
                },
                error: function() {
                    //请求出错处理
                }
            });
        }

        deleteCustomer(id) {
            $.ajax({
                url: "http://127.0.0.1:3000/customers/"+id,    //请求的url地址
                dataType: "json",   //返回格式为json
                async: true, //请求是否异步,默认为异步,这也是ajax重要特性
                type: "DELETE",   //请求方式
                beforeSend: function () {
                //请求前的处理
                },
                success: function (data) {
                    for (var i = 0; i < this.state.data.length; i++){
                        if(this.state.data[i].id==id){
                            this.state.data.splice(i,1);
                        }
                    }
                    this.setState({
                        loading: !this.state.loading
                    });
                alert("删除成功!");
                }.bind(this),
                complete: function () {
                //请求完成的处理
                },
                error: function () {
                //请求出错处理
                }
            });
        }

        render() {
            if (this.state.loading &this.state.data==null) {
                return <span>Loading.....</span>;
            } else {
            //请求成功时处理
                var htmlStrs = [];
                for (var i = 0; i < this.state.data.length; i++) {
                    var strings =<tr><td><span><a href='javascript:void(0)'>{this.state.data[i].id}</a></span></td><td><span>{this.state.data[i].customerName}</span></td><td><span>{this.state.data[i].contactName}</span></td><td><span>{this.state.data[i].phone}</span></td><td><button type='button' className='btn btn-danger' onClick={this.deleteCustomer.bind(this,this.state.data[i].id)}>delete</button></td></tr>;
                    htmlStrs.push(strings);
                }
                return (<table className="table table-bordered"><thead><tr><th>CustomerId</th><th>CompanyName</th><th>ContactName</th><th>Phone</th><th>Delete</th></tr></thead><tbody>{htmlStrs}</tbody></table>);
            }
        }
    };

    function btnAdd() {
        $("#dialog").show();
    }

    function addCustomer() {
        var customerObj = {};
        customerObj.customerName = $("#inputCustomerName").val();
        customerObj.contactName = $("#inputContactName").val();
        customerObj.phone = $("#inputPhone").val();

        $.ajax({
            url: "http://127.0.0.1:3000/customers",    //请求的url地址
            dataType: "json",   //返回格式为json
            data: customerObj,
            async: true, //请求是否异步,默认为异步,这也是ajax重要特性
            type: "POST",   //请求方式
            beforeSend: function () {
            //请求前的处理
            },
            success: function (data) {
            //请求成功时处理
            var htmlStr = '';
            for (var i = 0; i < data.length; i++) {
                htmlStr += "<tr><td><span><a href='javascript:void(0)'>" + data[i].id + "</a></span></td><td><span>" + data[i].customerName + "</span></td><td><span>" + data[i].contactName + "</span></td><td><span>" + data[i].phone + "</span></td><td><button type='button' class='btn btn-danger'>delete</button></td></tr>";
            }
            document.getElementById('tbody').innerHTML = htmlStr;
            },
            complete: function () {
            //请求完成的处理
            },
            error: function () {
            //请求出错处理
            }
        });
    }

    ReactDOM.render(
    <MyTitle /> ,
    document.getElementById('divTable'));
</script>
</body>
</html>
React+JSX

需要注意的地方:在JSX语法中,class关键字冲突,所以定义类名时用className替换,还需要注意在render中onClick事件的定义方式以及参数传递的实现方式。

在React组件中,如果State发生变化,组件会自动调用render方法重新生成返回值并刷新组件状态。

经测试,以上两种实现方式可以正常进行读取、写入、删除操作。

posted @ 2016-12-07 14:56  tzdk  阅读(1219)  评论(0编辑  收藏  举报