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

连接数据库

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>

  • 39
    点赞
  • 315
    收藏
    觉得还不错? 一键收藏
  • 15
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值