前端代码: (获取用户信息,并渲染页面) userinfor.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户信息</title>
    <script src='jquery-1.9.0.min.js'></script>
    <script src='vue.min.js'></script>
</head>
<body>
    <div id='app'>
        <p v-for='item in userList'><span>{{item.userName}}</span> <span> {{item.userTel}}</span></p>
    </div>   
</body>
    <script>
        new Vue({
            el: '#app',
            data: {
                userList: []
            },
            created: function () {
                var that = this;
                $.ajax({
                   type : "POST",
                              url : "./userinfor.php",
                              data : "",
                              success : function( data ) {
                                  var json = JSON.parse(data);
                                  if (json.flag) {
                                    that.userList = json.datalist;
                                  } else {
                                    alert(json.error_code);
                                  }
                              },
                              error : function(){
                                  lert("错误");
                              }
                })
            },
        })
    </script>
</html>

PHP代码: (查询数据库,并形成接口输出) userinfor.php

<?php
    header("Content-type: text/html; charset=utf-8");   //定义编码方式
    // 定义接口返回值
    $flag = 1;
    $error_code = '查询失败';
    $datalist = array();
 
    $host = '43.242.131.118'; //主机ip地址
    $user = 'hongmeng';  //主机用户
    $password = 'wyh19931106';  //主机用户密码
    $connection = mysql_connect($host, $user, $password); //连接主机
    if ( !$connection ) {
        die('连接失败');
    }
    $dbname = 'hongmeng_zl';  //数据库名
    mysql_select_db($dbname, $connection);  //连接数据库
    mysql_query("SET NAMES UTF8");  //MySQL字符编码
 
    $sql = "select `userName`,`userTel` from `userInfor` ";  //查询语句
    $result = mysql_query($sql);<br>
    if ( !$result ) {
        $flag = false;
        die('查询失败');
    };
     
    while ($row = mysql_fetch_assoc($result) ) {
    // while ($row = mysql_fetch_array($result) ) {
        $datalist[] = $row;   //将查询到的所有数据按行赋值给数组
    }
    // 返回json数据,或者字符串,数字。
    $json = array('flag' => $flag, 'error_code' => $error_code, 'datalist' => $datalist );<br> echo json_encode($json);  //将普通数组转换成json数组,(接口返回的值)
 
    mysql_close($connection); //断开数据库
 ?>
Last modification:December 3rd, 2019 at 12:45 pm
来杯coffee吧