连接数据库

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>

相关文章:

  • 2022-12-23
  • 2021-10-22
  • 2021-11-19
  • 2021-07-01
  • 2021-12-24
  • 2021-12-06
  • 2021-11-28
  • 2022-01-06
猜你喜欢
  • 2021-06-09
  • 2021-05-29
  • 2021-09-27
  • 2021-09-09
  • 2021-12-04
  • 2021-04-06
  • 2021-10-09
相关资源
相似解决方案