关于微信小程序的循环展示(后台PHP)

寒假的时候完成了一个基于微信小程序的车辆调度系统,其中的一个循环展示着实花费了不少时间去查阅网上各种各样的例子。现在我来分享一下我的经验。

.

这是前端的js,我用getApp().globalData.Username获取登录时候用户的用户名,传递到这个页面,方便之后传递后台去查询这个账户的信息。使用wx.request中的header的时候要注意,因为这个的method是get。还有一个叫'content-type': 'application/x-www-form-urlencoded',他的method是post。在我的代码中我省略了这个method。但在后台接收的时候就可以看出注意点了。还有最后的这个that.setdata里面的res.data意思就是接收后台发送的数组。待会再来看有什么用。

onLoad: function (options) {
    this.setData({
      Username: getApp().globalData.Username
    });
    var that = this;
    var username = getApp().globalData.Username;

    
    wx.request({
      url: 'http://localhost/query.php', //服务器地址
      data: {
        state1: "已批准",
        
        username: username,
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {



        that.setData({

          local_database: res.data,

        })
      }

    })


  },

贰.

这是后台代码,这里就要使用GET获取前端传递到后台的数据,如果前端的method是post,那这里就可能要用post了,接着连接数据库,找到相应的条件。然后设置一个class和一个array数组,把你要取的东西全部打包成数组。最后echo json_ehcode让数组打包为json格式发送到前端。

<?php
$state1=$_GET["state1"] ;

$Username=$_GET["username"] ;
$conn = mysqli_connect("localhost", "root","root","xcx");
$sql = "SELECT applicant,Place FROM application WHERE state ='$state1' and Username ='$Username'";
$result = mysqli_query($conn, $sql);

class Article{


public $applicant;
public $Place;

}
$data = array();
if (mysqli_num_rows($result) > 0) 
{
	while($row = mysqli_fetch_assoc($result)) {
		$article=new Article();

		$article->applicant=$row['applicant'];
		$article->Place=$row['Place'];
		
		$data[] = $article;
	}
	echo json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT);  //½«ÇëÇó½á¹ûת»»Îªjson¸ñʽ
}



?>

叁.

前端接收,这里注意的主要是wx:for里面的{{local_database}},它就是我们js里面的那个that.setdata接收的数组,一定要写的一样,不然没用。然后这个wx:key里面如果不写就默认为item,后面所有你想要循环展示的数据的开头都必须是wx:key里面的字符。代码我省略了一点方便大家观看

<block wx:for="{{local_database}}" wx:key=" ">
    <view class="post-container">
      <view class="orderDetails">
        <view class="orderListTitle">
          <text class="userName">申请人:{{item.applicant}} {{item.Id}}</text>
         <text class="orderStatus">目的地:{{item.Place}}</text>       
        </view>
        </view>  
    </view>
</block>

在下只是一名普通大一学生而已,新手上道,写的不是很完善,还希望在座的各位大佬不要嫌弃。

如果你有兴趣有梦想有人生信条的大学生,研究生或者就职大佬还请光临我们代码学习群交流:871352155。

后序

喜欢用HTML做成礼物或者贺卡等的朋友详情请看我的B站合集https://www.bilibili.com/video/av84894004不定时更新

发布了13 篇原创文章 · 获赞 39 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43341045/article/details/93417447