zoukankan      html  css  js  c++  java
  • [前后端交互][Vuejs+php] MySQL数据转JSON传值到前端

    说在前面

    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。

    优点如下[]:

    1.占带宽小(格式是压缩的)

    2. js通过eval()进行Json读取(便于客户端读取)

    3. JSON支持多种语言(c、c++、PHP等),便于服务端解析

    关键代码

    json_encode( $arr )  <文档传送门>
    ajax         <实例传送门>
     
    正文
    后台代码:
    <?php  
    include("/conn.php");
    //连接数据库
    header('Content-Type: text/html;charset=utf-8');
    header('Access-Control-Allow-Origin:*');
    header('Access-Control-Allow-Methods:*');
    header('Access-Control-Allow-Headers:x-requested-with,content-type');
    //设置允许JS跨域
    
    $sqlStr = "此处写SELECT等SQL语句";
    $sql=mysqli_query($link,$sqlStr);
    $info=mysqli_fetch_object($sql); 
    //查询结果并返回当前指针对象到$info(这里用的mysqli函数,实际也可以用PDO)
    
    do{ 
        $arr_temp = array(      //内层数组(类似结构体)内容中 数据名abcd 和 数据库字段名1234 只是便于理解,实际中要用英文做数据名。
            "数据名a"=>$info->数据库字段名1,
            "数据名b"=>$info->数据库字段名2,
            "数据名c"=>$info->数据库字段名3,
            "数据名d"=>$info->数据库字段名4
        ); 
        $json_arr[] = $arr_temp;  //外层数组
    }while($info=mysqli_fetch_object($sql));
    //遍历数据库,数组嵌套
    
    $json_obj = json_encode($json_arr);
    //数组转JSON格式
    
    echo $json_obj;
    //输出
    ?>     

    JS代码:

    首先需要直接引入vue,或者用npm在服务器安装vue环境。
    var words = new Vue({
            el:"#wordsBox",
            data:{
                items:[]
            },
            created: function () {
          //为了在内部函数能使用外部函数的this对象,要给它赋值了一个名叫self的变量。
                var self = this;
                $.ajax({
                    url: '此处填后台页面',
                    type: 'get',
                    data: {},
                    dataType: 'json',
                    success:function(data){
                        self.items = data;  //将后台传过来的json数据装入当前的items数组
                    },
                    error:function(){
                       console.log("failed to get:(");
                    }
                })
            }
        })

    HTML部分:(v-for把多层数组数据遍历出来。同上,数据名abc只是便于理解,实际代码数据名用英文)

    <tbody id="wordsBox">
      <tr class="wordDiv" v-for="item in items">
        <td v-text="item.数据名a"></td>
        <td v-text="item.数据名b"></td>
        <td v-text="item.数据名c"></td>
      </tr>
    </tbody>

    小功告成:)

    总结使人进步!

  • 相关阅读:
    Azure开发者任务之二:Cloud Service项目添加到ASP.Net Web中
    Azure开发者任务之一:解决Azure Storage Emulator初始化失败
    Configuring a Windows Azure Project
    How to manage the certificates in the PC
    在此声明我的博客已经搬到CSDN 中了
    http://www.cnblogs.com/Sniper-quay/archive/2011/06/22/2086636.html
    杂乱的UDPsocket
    socket下server端支持多客户端并发访问简单实现
    Qt 的udpSocket通信
    正则表达式
  • 原文地址:https://www.cnblogs.com/cc1997/p/10522678.html
Copyright © 2011-2022 走看看