连接数据库
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) } }) },
![](https://i-blog.csdnimg.cn/blog_migrate/9999f45e0f0f29fa582f3b1107ec0f37.png)
服务器处理包括接收的参数,数据库语句,返回的数据
<?php $name=$_REQUEST["name"] ;//接收参数 $con = mysqli_connect("120.132..190","root","Mcke123","didi"); if (!$con) { die('Could not connect: ' . mysqli_error()); }else{ echo $name; }
![](https://i-blog.csdnimg.cn/blog_migrate/4ce068bb1144b320d66c786db5f59469.png)
![](https://i-blog.csdnimg.cn/blog_migrate/832349bac6d4f3c636c94db22fc91b81.png)
到这里,我们的数据库连接就基本走通了!
请求方式(字符串数据)
// 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>