欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

微信小程序(六)实战——链接数据库

微信小程序(六)实战——链接数据库

2018年07月04日 15:57:17 开猿节流 阅读数:11497                
 版权声明:本文为博主原创文章,未经博主允许不得转载。交流联系QQ:634487911 https://blog.csdn.net/qq_38191191/article/details/80913933

连接数据库                

1.发起请求:                

微信小程序是以https方式提交数据到你的后台(案例为本地测试,暂时跳过)
               


               

onLoad: function () {
    wx.request({
      url: 'http://dev.cfo-mentor.com/menter/resources/views/demo/132.php', //服务器地址
        data: {
          name: 'bob'//请求参数
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res.data)
        }
      })
  },
                   

                   
2.服务器处理:
服务器处理包括接收的参数,数据库语句,返回的数据                
<?php
$name=$_REQUEST["name"] ;//接收参数
$con = mysqli_connect("120.132..190","root","Mcke123","didi");
if (!$con)
{
    die('Could not connect: ' . mysqli_error());
}else{
    echo $name;
}
                   

                   
打印结果:bob

               
到这里,我们的数据库连接就基本走通了!                


               

请求方式(字符串数据)


               

// OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT                

请求方式和接收方式必须相同

错误:


               

正确:


               


               

请求方式(数组数据)


               

页面显示:


               

代码:


               

<?php
//接收参数
$arr=array(
    'name'=>$_GET["name"],
    'age'=>$_GET["age"]
    );
$con = mysqli_connect("120.132.20.190","root","Mckenzie123","didi");
if (!$con)
{
    die('Could not connect: ' . mysqli_error());
}else{
    echo json_encode($arr);
}


onLoad: function () {
    var that = this;//=====注意此处,要用that 指代this=====
    wx.request({
      url: 'http://dev.cfo-mentor.com/menter/resources/views/demo/132.php', //服务器地址
      method: 'get',// OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      data: {
        name: 'bob',//请求参数
         age: '12'//请求参数
      },
      header: {// 设置请求的 header
        'content-type': 'application/json'
      },
      success: function (res) {
        that.setData({ //======不能直接写this.setDate======
          message: res.data, //在相应的wxml页面显示接收到的数据
        });
      }
    })
  },



<view>我是后台传过来的{{message}}</view>
<view>我是后台传过来的{{message.name}}</view>
<view>我是后台传过来的{{message.age}}</view>

           


普通分类: