jq-ajax与node后台的数据交互

引用段落,本次代码演示的只有留言板的添加信息功能
思想方法:通过填写内容点击提交按钮,触发add请求,后台返回成功信息并且将数据存在Map之中,在add success回调函数中再调用obj.getlLst()方法,发送get请求,后台返回Map的数据,前端通过遍历数据显示在ul之中。

html部分:


 
 
     js实现简单留言板
     
     
      
     
     
  
  
     
留言列表

请求部分代码:

let obj ={
  //m:new Map(),
  init:function(){
    this.bind();
  },
  bind:function(){
        $(".container .submit").click(()=>{
            let _name = $(".name").val(),
                _msg = $(".message").val();
            if(_name =='' || _msg ==''){
                alert('请输入信息')
            }else {
                //this.m.set(_name,_msg);
                this.add(_name,_msg);
                $(".name,.message").val('');
            }
        });
    },
  add:function(name,msg){
    var self = this;
    $.ajax({
      type:'post',
      url:'http://localhost:3000/add',
      async:true,  //异步
      dataType:'json',
      data:{name:name,message:msg},
      success:function(res){  //后端返回的值
         if(res.code == '200'){
           obj.getList();
         }
      },
      error:function(){
        alert(1);
      }
    })
  },
  getList:function(name,msg){
        var self = this;
        $.ajax({
          type:'get',
          url:'http://localhost:3000/get',
          sync:true,
          dataType:'json',
          success:function(res){
            if(res.code == '200'){
             let str = '';
             for(let item of res.result){
              str += `
  • ${item.name}说:${item.message}
  • ` }; $(".messageList").html(str); } } }) }, } $(function(){ obj.init(); })

    node端代码:

    引用段落,注意:运行node端需要安装中间件的依赖,通过提示缺失的包,使用cmd中npm install xxx即可,运行方法:node server-run.js(node文件的名称)

    var connect = require('connect');  //创建连接
    var bodyParser = require('body-parser');   //body解析
    var m = new Map();
    //map转为数组对象
    function mapToArr(m){
        var arr = [];
        for(let [key,value] of m){
            arr.push({name:key,message:value})
        };
        return arr;
    };
    
    var app = connect()
        .use(bodyParser.json())   //JSON解析
        .use(bodyParser.urlencoded({extended: true}))
        //use()方法还有一个可选的路径字符串,对传入请求的URL的开始匹配。
        //use方法来维护一个中间件队列
        .use(function (req, res, next) {
            //跨域处理
            // Website you wish to allow to connect
            res.setHeader('Access-Control-Allow-Origin', '*');  //允许任何源
            // Request methods you wish to allow
            res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');  //允许任何方法
            // Request headers you wish to allow
            res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,X-Session-Token');   //允许任何类型
            res.writeHead(200, {"Content-Type": "text/plain;charset=utf-8"});    //utf-8转码
            next();  //next 方法就是一个递归调用
        })
        .use('/add', function(req, res, next) {
              console.log(req.body);
          m.set(req.body.name,req.body.message);
          var data = {
            "code": "200",
            "msg": "success"
          };
          res.end(JSON.stringify(data));
          next();
            //m.set(req.body.name,req.body.message);
            //var data = {
            //  "code": "200",
            //  "msg": "success"
            //};
            //res.end(JSON.stringify(data));
            //next();
        //
        })
        .use('/get', function(req, res, next) {
            var data={
                "code": "200",
                "msg": "success",
                "result": mapToArr(m)
            };
            res.end(JSON.stringify(data));
    
            next();      //
        })
        .use('/get_query', function(req, res, next) {
            var data={
                "code": "200",
                "msg": "success",
                "result":{"id":1}
            };
            res.end(JSON.stringify(data));
            next();      //
        })
        .listen(3000);   //
    console.log('Server started on port 3000.');
    

    运行效果:

    1.add请求成功:
    图1.add请求

    2.get请求成功:
    图2.get请求

    3.页面显示:
    图3.页面渲染成功

    4.node端打印:
    图4.node端显示

    你可能感兴趣的:(jq-ajax与node后台的数据交互)