纵有疾风起
人生不言弃

小程序请求网络数据并填充到首页列表

点击下面网址进入视频讲解教程

视频讲解

上一节带领大家实现了网络数据的获取,这节就来带大家解析我们获取到的json数据,并把数据填充到我们的页面上。

学前准备

  • 1,需要了解css(只需要了解就行)
  • 2,需要对上一节的代码有初步了解。

我们本节代码完全基于上节代码
上一节课传送门

本节知识点

  • 1,网络数据的解析
  • 2,填充网络数据到我们到首页列表
  • 3,css的简单使用(让页面好看起来)

一,解析网络请求到的数据

小程序请求网络数据并填充到首页列表插图
获取到的网络数据

上图是我们上一节获取到的网络数据在调试器里的打印。
我们对获取到的数据做下格式化,如下

{    "code": 100,    "msg": "成功",    "data": [        {            "aid": 0,            "title": "零基础入门小程序001----开发属于自己的第一个小程序",            "content": "小程序开发我们需要下载相应的开发工具,个人比较推荐的是微信官方出的开发工具。毕竟是官方工具。\n首先贴出官方开发工具下载地址:https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html\n![01工具下载.png](https://upload-images.jianshu.io/upload_images/6273713-0f774502ce9d4611.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n至于怎么安装就不用我说了。下载下来后双击就可以安装了。安装后需要扫码登录。扫码登录后的界面如下。\n![02登录开发工具.png](https://upload-images.jianshu.io/upload_images/6273713-721073420e921d8b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n项目名字可以随便填,很多刚入门小程序开发的人会有疑虑,我没有注册小程序能直接开发吗。这里明确的告诉你,没有注册小程序也是可以学习开发小程序的。只需要按照我上图所示点击无appid体验即可。\n\n## 下面是小程序开发工具的界面\n![03开发工具界面.png](https://upload-images.jianshu.io/upload_images/6273713-35148460e75e8fc9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n到这里我们的武器便装备好了,接下来开始为武器填充子弹了。\n## 接下来带领大家零基础入门自己的第一个简单小程序。\n由于是入门所以我们的小程序比较简单主要包含以下功能\n- 两个页面:首页,个人中心页\n- 底部tab实现\n- 顶部标题设置\n![04项目效果.png](https://upload-images.jianshu.io/upload_images/6273713-5481bafc1e622dbb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n### 一,代码目录\n![05项目目录.png](https://upload-images.jianshu.io/upload_images/6273713-3618fd258b6bde3c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n### 二,展开讲解\n- images:目录用来存放一些我们的图片资源,如项目里底部tab的图标,就放在这里。\n- pages: 这里是我们写小程序的主要代码目录,目前我们有两个页面首页和个人中心页。\n- app.json: 我们小程序的一些全局配置都在这里。如我们底部的两个tab就是在这里配置的。\n\n### 三,小程序开发三剑客\n我们开发小程序需要创建三个对应的文件,比如我们创建首页index。在index下需要创建如下三个文件\n![06.png](https://upload-images.jianshu.io/upload_images/6273713-109a76de567e8393.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n这三个文件就是我们开发小程序必不可少的三剑客\n- index.wxml:确定首页的大体模样。比如我们建大楼,这里的代码来确定楼长什么样,多高,多宽,多少层等。\n- index.wxss:这里主要做一些样式的设置,如我们的楼外观,需要贴什么样的瓷砖,刷什么颜色。\n- index.js:用来处理我们首页的一些事件,让首页具备某些能力。如我们楼里有游乐场,电影院等。通过js来处理这些事件。\n这就是我们首页的大致。下面带大家看下简单代码\n```\n<!--index.wxml-->\n<view style=\"color:blue; \">\n  我是传说中的首页\n</view>\n```\n这就是index.wxml,这里我们只是简单展示一段话。\nindex.wxss和index.js用的是默认的,没有什么东西,这里就不贴出来了,大家想看可以下载源码看。\n\n### 四,看下app.json都配置了些什么\n```\n// app.json\n{\n  // 设置我们小程序的页面:首页,个人中心\n  \"pages\": [\n    \"pages/index/index\",\n    \"pages/me/me\"\n  ],\n  // 设置标题栏字体颜色等信息\n  \"window\": {\n    \"backgroundTextStyle\": \"light\",\n    \"navigationBarBackgroundColor\": \"#fff\",\n    \"navigationBarTitleText\": \"30天入门小程序01\",\n    \"navigationBarTextStyle\": \"black\"\n  },\n  // 底部模块tab\n \"tabBar\": {\n   \"list\": [{\n     \"pagePath\": \"pages/index/index\",\n     \"text\": \"首页\",\n     \"iconPath\": \"/images/tab1n.png\",\n     \"selectedIconPath\": \"/images/tab1y.png\"\n   },\n   {\n      \"pagePath\": \"pages/me/me\",\n      \"text\": \"我的\",\n      \"iconPath\": \"/images/tab2n.png\",\n      \"selectedIconPath\": \"/images/tab2y.png\"\n\n   }]\n }\n}\n```\n\n 个人中心里的代码就不贴出来啦,大家下载源码看下就行。\n\n#### 入门第一节课,不需要大家知道太多,按照源码里,大致看下,了解下小程序的代码长什么样子就行。其实很简单。\n今天就到这里,接下来的课程我会尽量录成视频,感觉文章不太形象。对于新手来说,视频学起来可能效率更高些。\n\n\n我以后会把每一节的代码放到百度网盘供大家下载\n源码:https://pan.baidu.com/s/1uG63tvDj41KlRvGMe3NNSg  密码:i778\n如果连接失效请加我微信2501902696(备注小程序)",            "readNum": "1111",            "createTime": "2018-04-27 19:55:49.0",            "author": "小石头",            "classify": "零基础学小程序"        },        {            "aid": 1,            "title": "零基础入门小程序002---开发简单的计算器",            "content": "上一节和大家一起写出了属于自己的第一个小程序,这节就带大家写出自己的第一个简单计算器。由于是入门,这里先教大家简单的加法运算。效果图如下![1.png](https://upload-images.jianshu.io/upload_images/6273713-2f2c73e17776c8fb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n实现起来特别简单,代码也特别少,就下面三个\n- index.wxml:上图的布局视图页\n- index.js:实现加法逻辑的页面\n- app.json:一些全局的配置。基本是都是默认的这里不用管\n![0.png](https://upload-images.jianshu.io/upload_images/6273713-2b8639cf9f1fc8ea.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n下面就带带大家敲出属于自己的计算器小程序代码。\n### 1,先看index.wxml,是不是代码特别少\n```\n<!--index.wxml  -->\n<input placeholder=\"请输入数字a\" bindinput=\"inputa\" />\n<text>+</text>\n<input placeholder=\"请输入数字b\" bindinput=\"inputb\" />\n<button bindtap='sum'>计算</button>\n<text>结果为:{{result}}</text>\n```\n代码虽然少,但是作为刚入门的你,看起来可能很茫然,下面详细给大家讲下。\n```\n<input placeholder=\"请输入数字a\" bindinput=\"inputa\" /> \n<input placeholder=\"请输入数字b\" bindinput=\"inputb\" />\n```\n就是我们输入数字a的输入框,这里input就是我们认识的第一个小程序组件。\ninput的官方简介如下:https://developers.weixin.qq.com/miniprogram/dev/component/input.html\nplaceholder:设置默认显示文字(当我们输入文字时,默认的就没有了)\nbindinput=\"inputa\":定义一个inputa方法来获取input的输入内容。在index.js中会用到\n- <text>+</text> \n这里的<text>组件是用来显示文本的这里我们只是为了显示一个 + 号\n```\n<button bindtap='sum'>计算</button>\n```\n这里是个按钮<button>就是我们的计算按钮\nbindtap='sum':定义个叫sum的方法,用来计算结果在index.js中会用到\n\n- <text>结果为:{{result}}</text>\n{{result}}  这种写法,是小程序用来绑定数据用的,这里用来显示我们的计算结果用的,\n#### 上面代码和对应的显示如下:\n![4.jpg](https://upload-images.jianshu.io/upload_images/6273713-cb3653260d35d837.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n## 2,再来看index.js,我们加法的逻辑实现\n可以看到我们在index.wxml里定义的bindinput=\"inputa\",bindtap='sum'在下面有用到\n```\nPage({\n  /**\n     * 页面的初始数据\n     * 初始化两个输入值\n     */\n  data: {\n    input1: 0,\n    input2: 0\n  },\n  //获取用户输入的值a\n  inputa: function (e) {\n    this.setData({\n      input1: e.detail.value\n    })\n  },\n  //获取用户输入的值b\n  inputb: function (e) {\n    this.setData({\n      input2: e.detail.value\n    })\n  },\n  // 拿到两个输入值以后求和\n  sum: function (e) {\n    var a = parseInt(this.data.input1);\n    var b = parseInt(this.data.input2);\n    // 求和\n    var sumResult = a + b\n    this.setData({\n      // 把结果赋值到sum标签上\n      result: sumResult\n    })\n  }\n})\n```\nindex.js的代码不多,大家可以先照着敲一下。学小程序前期不需要你理解,但是一定要多敲多练。\n这里的逻辑用文字写出来,估计大家新入门时还是不太好理解,我会录视频来给大家讲解。\n源码地址:链接:https://pan.baidu.com/s/1ulgabXKwXh5vu7DHUOyNNQ  密码:ud86\n有问题加我微信:2501902696\n\n\n\n\n###系列课程\n- [零基础入门小程序001----开发属于自己的第一个小程序](https://www.jianshu.com/p/275eaf4d1921)",            "readNum": "111",            "createTime": "2018-04-27 19:58:15.0",            "author": "小石头",            "classify": "零基础学小程序"        },        {            "aid": 2,            "title": "零基础学小程序003----请求服务器数据,请求后台json数据",            "content": "我们开发小程序,肯定不是简简单单的写一些页面,肯定会设计到一些和后台服务器的交互,今天就带大家来学习小程序请求后台数据。\n学习要点\n- 1,通过https请求后台数据\n- 2,解析json数据\n- 3,获取https数据\n\n接口url:\nhttps://30paotui.com\nhttps://30paotui.com/buyer/product/list\n\n### 一,我们通常请求后台的数据如下:\n\n![image](http://upload-images.jianshu.io/upload_images/6273713-bf473d1d8930c52f?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n![image](http://upload-images.jianshu.io/upload_images/6273713-15df2d623e5dc533?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n就是通过后台提供一个接口url,然后我们通过http获取https请求获取到后台数据,或则提交一些数据给后台。\n\n### 二,小程序请求后台json数据代码实现\n\n先看效果图\n\n![image](http://upload-images.jianshu.io/upload_images/6273713-1ab5190797618b56?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n实现代码api.js\n```\n\nPage({\n\n  /**\n   * 页面的初始数据\n   */\n  data: {\n    \n  },\n  //请求简单数据\n  getData:function(e){\n    console.log('开始加载服务器数据')\n    var that = this;\n    var jsonStr = \"\";\n    wx.request({\n      url: 'https://30paotui.com',\n      header: {\n        'content-type': 'application/json' // 默认值\n      },\n      success: function (res) {\n        console.log(res.data)\n        //json对象转字符串\n        jsonStr = JSON.stringify(res.data)\n\n        that.setData({\n          text: '后台返回的数据如下: \\n'+jsonStr,\n        })\n      }\n\n    })\n  },\n//请求复杂json数据\n  getjson: function (e) {\n    console.log('开始加载服务器数据')\n    var that = this;\n    var jsonStr = \"\";\n    wx.request({\n      url: 'https://30paotui.com/buyer/product/list',\n      header: {\n        'content-type': 'application/json' // 默认值\n      },\n      success: function (res) {\n        console.log(res.data)\n        //json对象转字符串\n        jsonStr = JSON.stringify(res.data)\n\n        that.setData({\n          json: '后台返回的数据如下: \\n' + jsonStr,\n        })\n      }\n\n    })\n  },\n\n\n})\n```\napi.wxml\n```\n<button bindtap='getData'>https请求简单数据</button>\n<text>{{text}}</text>\n<button bindtap='getjson'>请求后台json数据</button>\n<text>{{json}}</text>\n```\n\n![代码结构.png](https://upload-images.jianshu.io/upload_images/6273713-3718629b92cfbd9b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n由于是入门,所以代码特别少,但是基本的请求后台数据的功能都实现了\n\n源码连接链接:百度网盘\nhttps://pan.baidu.com/s/12tnVDLy_usvw_r6Zg9ilgQ  密码:4g9c\n",            "readNum": "1234",            "createTime": "2018-04-27 20:02:05.0",            "author": "小石头",            "classify": "零基础学小程序"        },        {            "aid": 3,            "title": "零基础学小程序004----小程序post请求,提交数据到服务器,小程序下单,小程序用户注册功能",            "content": "由于这段时间工作比较忙,小程序入门系列课程一直没有更新,今天好不容易抽个时间来更新系列教程,今天的这个教程对大家很有用,涉及到和后台服务器的数据交互。\n- 不多说,先看效果图\n![提交订单到后台.gif](https://upload-images.jianshu.io/upload_images/6273713-27db2bed226048ea.gif?imageMogr2/auto-orient/strip)\n### 技术要点\n- 姓名,手机号,地址为空验证\n- post请求\n- 简单的下单功能实现\n- api数据解析\n- post提交参数有数组时的问题解决\n\n## 一,简单页面布局\n简单的把页面布局写出来\n```\n<!-- order.wxml -->\n<view class=\"login\">\n  <form bindsubmit=\"formSubmit\">\n    <input name=\"name\" class=\"login-input\" type=\"text\" placeholder=\"请输入姓名\" />\n    <input name=\"mobile\" class=\"login-input\" type=\"number\" placeholder=\"请输入手机号\" />\n    <input name=\"address\" class=\"login-input\" type=\"text\" placeholder=\"请输入地址\" />\n    <button class=\"btn_login\" formType=\"submit\">提交订单</button>\n  </form>\n</view>\n```\n主要是几个input输入框\n\n## 二,做提交数据的简单校验\n```\n    if (e.detail.value.name.length == 0) {\n      this.showErrorToast('姓名不能为空')\n    } else if (e.detail.value.mobile.length == 0) {\n      this.showErrorToast('手机号不能为空')\n    } else if (e.detail.value.mobile.length != 11) {\n      this.showErrorToast('请输入11位手机号码')\n    } else if (e.detail.value.address.length ==0) {\n      this.showErrorToast('地址不能为空!')\n    } \n```\n 主要判断name,phone,address是否为空,手机号是否符合11位。\n\n## 三,先说一下api\nurl:https://30paotui.com/buyer/order/create\n请求类型:post\n提交参数格式如下\n```\nopenid:小程序小石头\nphone:12345678901\nname:夏天\naddress:杭州市临平街道\nitems:[{productId:1,productQuantity:2},{productId:2,productQuantity:2}]\n ```\npost请求后服务器返回json如下\n  - 成功\n```\n{\n    \"code\": 100,\n    \"msg\": \"成功\",\n    \"data\": {\n        \"orderID\": \"1529819130135395193\"\n    }\n}\n```\n  - 失败\n```\n{\n    \"timestamp\": \"2018-06-24T04:34:33.413+0000\",\n    \"status\": 500,\n    \"error\": \"Internal Server Error\",\n    \"message\": \"微信id必传\",\n    \"path\": \"/buyer/order/create\"\n}\n```\n比如我openid参数传空\n![失败请求模拟.png](https://upload-images.jianshu.io/upload_images/6273713-4dfb7d17711e92f8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n## 四,提交数据到服务器(下单)\n这里是重点,不管是注册用户,用户提交订单,提交数据到后台都是一样的原理,把这里学会了,你以后再做数据提交也就都会了\n```\nformSubmit: function(e) {\n    if (e.detail.value.name.length == 0) {\n      this.showErrorToast('姓名不能为空')\n    } else if (e.detail.value.mobile.length == 0) {\n      this.showErrorToast('手机号不能为空')\n    } else if (e.detail.value.mobile.length != 11) {\n      this.showErrorToast('请输入11位手机号码')\n    } else if (e.detail.value.address.length ==0) {\n      this.showErrorToast('地址不能为空!')\n    } else {\n      // post提交表单\n      wx.request({\n        url: 'https://30paotui.com/buyer/order/create',\n        header: {\n          \"Content-Type\": \"application/x-www-form-urlencoded\"\n        },\n        method: \"POST\",\n        data: {\n          openid: 'qclqclqcl', //这里先写死微信id\n          phone: e.detail.value.mobile,\n          name: e.detail.value.name,\n          address: e.detail.value.address,\n          items: JSON.stringify([{\n            productId: 1,\n            productQuantity: 2\n          }, {\n            productId: 2,\n            productQuantity: 2\n          }])\n        },\n        success: function(res) {\n          console.log(res)\n          if (res.statusCode != 200) {\n            wx.showToast({ //这里提示失败原因\n              title: res.data.message,\n              icon: 'loading',\n              duration: 1500\n            })\n          } else {\n            wx.showToast({\n              title: '订单提交成功', //这里成功\n              icon: 'success',\n              duration: 1000\n            })\n          }\n        },\n        fail: function(res) {\n          console.log(fail)\n          wx.showToast({\n            title: '请求失败',\n            icon: 'none',\n            duration: 1500\n          })\n        }\n\n      })\n    }\n  },\n```\n #### 几点注意\n- 1,这里的formSubmit函数名对应wxml文件里的\n```\n <form bindsubmit=\"formSubmit\">\n```\n- 2,post提交的参数中有数组的话,需要用JSON.stringify()方法把数组转化为string\n```\nitems: JSON.stringify([{\n            productId: 1,\n            productQuantity: 2\n          }, {\n            productId: 2,\n            productQuantity: 2\n}])\n```\n\n到这里就可以实现下单功能了\n\n### 下面贴出来完整代码\n```\n// order.js\nPage({\n  data: {},\n  showErrorToast: function(e) {\n    wx.showModal({\n      title: '提示!',\n      confirmText: '朕知道了',\n      showCancel: false,\n      content: e,\n      success: function(res) {\n        if (res.confirm) {\n          console.log('用户点击确定')\n        }\n      }\n    })\n  },\n  formSubmit: function(e) {\n    if (e.detail.value.name.length == 0) {\n      this.showErrorToast('姓名不能为空')\n    } else if (e.detail.value.mobile.length == 0) {\n      this.showErrorToast('手机号不能为空')\n    } else if (e.detail.value.mobile.length != 11) {\n      this.showErrorToast('请输入11位手机号码')\n    } else if (e.detail.value.address.length ==0) {\n      this.showErrorToast('地址不能为空!')\n    } else {\n      // post提交表单\n      wx.request({\n        url: 'https://30paotui.com/buyer/order/create',\n        header: {\n          \"Content-Type\": \"application/x-www-form-urlencoded\"\n        },\n        method: \"POST\",\n        data: {\n          openid: 'qclqclqcl', //这里先写死微信id\n          phone: e.detail.value.mobile,\n          name: e.detail.value.name,\n          address: e.detail.value.address,\n          items: JSON.stringify([{\n            productId: 1,\n            productQuantity: 2\n          }, {\n            productId: 2,\n            productQuantity: 2\n          }])\n        },\n        success: function(res) {\n          console.log(res)\n          if (res.statusCode != 200) {\n            wx.showToast({ //这里提示失败原因\n              title: res.data.message,\n              icon: 'loading',\n              duration: 1500\n            })\n          } else {\n            wx.showToast({\n              title: '订单提交成功', //这里成功\n              icon: 'success',\n              duration: 1000\n            })\n          }\n        },\n        fail: function(res) {\n          console.log(fail)\n          wx.showToast({\n            title: '请求失败',\n            icon: 'none',\n            duration: 1500\n          })\n        }\n\n      })\n    }\n  },\n})\n```\n下图是数据提交成功后,服务器上的数据\n![后台数据.png](https://upload-images.jianshu.io/upload_images/6273713-b09c78d230fee05b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",            "readNum": "1111",            "createTime": "2018-06-24 13:56:48.0",            "author": "小石头",            "classify": "零基础学小程序"        },        {            "aid": 4,            "title": "零基础学小程序005---小程序登陆注册功能实现",            "content": "上一节给大家将来post提交数据,如果没看的请移步下面\n[零基础学小程序004----小程序post请求,提交数据到服务器,小程序下单,小程序用户注册功能](https://www.jianshu.com/p/a6eb370d60c7)\n上一节虽然有提到小程序用户注册与登陆功能,但是篇幅有限,就没详细写。今天就来给大家详细讲解下小程序的注册与登陆功能实现。\n- 不多说,先看效果图\n![小程序登陆与注册实现.gif](https://upload-images.jianshu.io/upload_images/6273713-24364f8762e1387e.gif?imageMogr2/auto-orient/strip)\n\n# 实现功能点\n- 1,输入内容的获取\n- 2,注册功能\n- 3,登陆功能\n下面就逐个功能点给大家讲解。\n# 先说下登陆和注册的基本原理\n登陆和注册,肯定需要我们获取输入的用户名和密码。然后把用户名和密码传到服务器后台,后台把用户名和密码存到数据库里,存入成功就返回注册成功的信息,\n以后登陆时就可以直接查询用户是否存在,存在就比对密码,如果密码一致,就返回登陆成功的信息。\n# 一,获取输入内容\n先看下布局index.xml\n```\n<!--index.wxml-->\n<input class='inputA' placeholder=\"请输入用户名\" bindinput=\"inputName\" />\n<input class='inputA' placeholder=\"请输入密码\" password='true' bindinput=\"inputPassword\" />\n<button wx:if=\"{{!isLogin}}\" type='primary' bindtap='register'>注册</button>\n<button wx:if=\"{{isLogin}}\" type='primary' bindtap='login'>登陆</button>\n```\n注意点:\n- bindinput=\"inputName\"  中的inputName对应index.js里的inputName()函数,用来获取输入的用户名\n- bindinput=\"inputPassword\"   中的inputPassword对应index.js里的inputPassword()函数,用来获取输入的用户名\n下面贴出这两个函数\n```\n //获取用户输入的值a\n inputName: function(e) {\n  inputName = e.detail.value;\n },\n //获取用户输入的值b\n inputPassword: function(e) {\n  inputPassword = e.detail.value;\n  console.log(\"输入的密码:\" + inputPassword);\n },\n```\n到这里我们就可以获取到输入的用户名和密码了。\n\n# 二,对输入的用户名和密码做校验\n注意校验用户名不能为空,密码不能为空,密码不能少于6位数。\n校验代码如下:\n```\n //检测输入值\n checkInput: function() {\n  if (inputName == \"\" || inputName == null ||\n   inputName == undefined) {\n   this.showErrorToastUtils('请输入用户名');\n  } else if (inputPassword == \"\" || inputPassword == null || inputPassword == undefined) {\n   this.showErrorToastUtils('请输入密码');\n  } else if (inputPassword.length < 6) {\n   this.showErrorToastUtils('密码至少要6位');\n  }\n  return true;\n },\n```\n当用户名和密码都符合规则时,返回true。说明输入的用户名和密码合法。\n\n# 三,注册功能的实现\n注册就需要我们请求后台注册接口了。\n```\n // 注册\n register: function() {\n  var that = this;\n  var isrightful = that.checkInput();\n  if (isrightful) {\n   wx.request({\n    url: 'http://localhost:8080/user/testSave',\n    header: {\n     \"Content-Type\": \"application/x-www-form-urlencoded\"\n    },\n    method: \"POST\",\n    data: {\n     name: inputName,\n     password: inputPassword\n    },\n    success: function(res) {\n     console.log(res)\n     if (res.statusCode != 200) {\n      wx.showToast({ //这里提示失败原因\n       title: res.data.message,\n       icon: 'loading',\n       duration: 1500\n      })\n     } else {\n      wx.showToast({\n       title: '注册成功', //这里成功\n       icon: 'success',\n       duration: 1000\n      });\n      that.setData({\n       isLogin: true,\n      }\n      )\n     }\n    },\n    fail: function(res) {\n     console.log(res)\n     wx.showToast({\n      title: '请求失败',\n      icon: 'none',\n      duration: 1500\n     })\n    }\n   });\n  }\n },\n```\n注意点:\nif (res.statusCode != 200) 这里我们判断后台返回的statusCode,只有statusCode等于200时,才说明我们注册成功,下面时注册成功后后台返回的信息\n![注册成功.png](https://upload-images.jianshu.io/upload_images/6273713-63dd384862c99f2e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n# 四,登陆功能实现\n登陆其实和注册都是把用户名和密码传到后台,只不过登陆时,先那用户名去数据库里查,看是否存在这个用户。\n如果存在,就去比对我们传的密码和数据库里存的密码是否一样,如果一样就登陆成功,返回登陆信息。\n![登陆成功.png](https://upload-images.jianshu.io/upload_images/6273713-281001cd7526f89c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n## 下面贴出完整代码index.js\n```\nvar inputName = \"\";\nvar inputPassword = \"\";\nPage({\n /**\n  * 页面的初始数据\n  * 初始化两个输入值\n  */\n data: {\n  isLogin: false\n },\n //获取用户输入的值a\n inputName: function(e) {\n  inputName = e.detail.value;\n },\n //获取用户输入的值b\n inputPassword: function(e) {\n  inputPassword = e.detail.value;\n  console.log(\"输入的密码:\" + inputPassword);\n },\n // 注册\n register: function() {\n  var that = this;\n  var isrightful = that.checkInput();\n  if (isrightful) {\n   wx.request({\n    url: 'http://localhost:8080/user/testSave',\n    header: {\n     \"Content-Type\": \"application/x-www-form-urlencoded\"\n    },\n    method: \"POST\",\n    data: {\n     name: inputName,\n     password: inputPassword\n    },\n    success: function(res) {\n     console.log(res)\n     if (res.statusCode != 200) {\n      wx.showToast({ //这里提示失败原因\n       title: res.data.message,\n       icon: 'loading',\n       duration: 1500\n      })\n     } else {\n      wx.showToast({\n       title: '注册成功', //这里成功\n       icon: 'success',\n       duration: 1000\n      });\n      that.setData({\n       isLogin: true,\n      }\n      )\n     }\n    },\n    fail: function(res) {\n     console.log(res)\n     wx.showToast({\n      title: '请求失败',\n      icon: 'none',\n      duration: 1500\n     })\n    }\n   });\n  }\n },\n // 登陆\n login: function() {\n  var that = this;\n  var isrightful = that.checkInput();\n  if (isrightful) {\n   wx.request({\n    url: 'http://localhost:8080/user/testLogin',\n    header: {\n     \"Content-Type\": \"application/x-www-form-urlencoded\"\n    },\n    method: \"POST\",\n    data: {\n     name: inputName,\n     password: inputPassword\n    },\n    success: function(res) {\n     console.log(res)\n     if (res.statusCode != 200) {\n      wx.showToast({ //这里提示失败原因\n       title: res.data.message,\n       icon: 'loading',\n       duration: 1500\n      })\n     } else {\n      wx.showToast({\n       title: '登陆成功', //这里成功\n       icon: 'success',\n       duration: 1000\n      });\n      that.setData({\n       isLogin: true,\n      }\n      )\n     }\n    },\n    fail: function(res) {\n     console.log(res)\n     wx.showToast({\n      title: '请求失败',\n      icon: 'none',\n      duration: 1500\n     })\n    }\n   });\n  }\n },\n //检测输入值\n checkInput: function() {\n  if (inputName == \"\" || inputName == null ||\n   inputName == undefined) {\n   this.showErrorToastUtils('请输入用户名');\n  } else if (inputPassword == \"\" || inputPassword == null || inputPassword == undefined) {\n   this.showErrorToastUtils('请输入密码');\n  } else if (inputPassword.length < 6) {\n   this.showErrorToastUtils('密码至少要6位');\n  }\n  return true;\n },\n\n // 错误提示\n showErrorToastUtils: function(e) {\n  wx.showModal({\n   title: '提示!',\n   confirmText: '朕知道了',\n   showCancel: false,\n   content: e,\n   success: function(res) {\n    if (res.confirm) {\n     console.log('用户点击确定')\n    }\n   }\n  })\n },\n})\n```\n到此我们的小程序注册与登陆功能就实现了。\n如果有问题可以加我微信2501902696(备注小程序)\n想要源码也可以加我微信\n\n扫描识别下面小程序码,学习更多零基础入门小程序的课程。\n![编程学习.jpg](https://upload-images.jianshu.io/upload_images/6273713-22f8783b1ccfe8d8.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n",            "readNum": "1000",            "createTime": "2018-08-07 16:01:12.0",            "author": "小石头",            "classify": "零基础学小程序"        },        {            "aid": 5,            "title": "零基础学小程序006---小程序获取用户信息用户昵称",            "content": "上一节给大家讲了[零基础学小程序005---小程序登陆注册功能实现](https://www.jianshu.com/p/d859b37eb2fd)。我们有时候只需要获取到微信用户的用户名和用户信息就可以了,不一定非得让用户去注册。所以这一节来给大家讲一下如何获取用户信息。\n先来看下请求到的结果\n![获取用户信息.png](https://upload-images.jianshu.io/upload_images/6273713-7a506cdf713c6982.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n目前微信提供的获取用户信息的方式主要是下面两种方式\n- 1,通过wx.getUserInfo\n```\nwx.getUserInfo({\n      success: function(res) {\n           console.log(res.userInfo)\n      }\n})\n```\n- 2,通过<button open-type=\"getUserInfo\" ></button>\n\n用于第一种方式,微信现在不在给弹窗提示了,所以推荐使用第二种方式\n![微信api.png](https://upload-images.jianshu.io/upload_images/6273713-0ea833ea69a3907e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n下面就来讲下用第二种方式如何获取用户信息\n主要实现代码如下\n```\n//user.wxml里布局\n<button open-type=\"getUserInfo\" \n  type=\"primary\" bindgetuserinfo=\"onGotUserInfo\">\n获取用户信息\n</button>\n\n // button获取用户信息\n onGotUserInfo: function(e) {\n  if (e.detail.userInfo) {\n   var user = e.detail.userInfo;\n   app._saveUserInfo(user);\n  } else {\n   console.log(\"用户拒绝了登陆\");\n  }\n },\n```\n我们通过设置open-type=\"getUserInfo\" 来实现点击登陆按钮时获取用户信息,\n通过bindgetuserinfo=\"onGotUserInfo\"来把获取到的用户信息传递到js文件里,进而做一些后续操作。\n\n当我们点击登陆按钮时,会有如下弹窗\n![用户拒绝登陆.png](https://upload-images.jianshu.io/upload_images/6273713-dc7bdf7e67ea51b6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n如果用户点拒绝登陆,我们可以提醒用户。如果用户点击允许我们就可以获取到用户的信息了。\n###下面就是我们获取到到用户信息\n```\n{nickName: \"小程序小游戏开发\", gender: 1, language: \"zh_CN\", city: \"Hangzhou\", province: \"Zhejiang\", …}\n```\n到此我们就实现了小程序获取用户信息的功能了,是不是很简单。\n\n扫描识别下面小程序码,学习更多零基础入门小程序的课程。\n\n![小程序学习.jpeg](https://upload-images.jianshu.io/upload_images/6273713-a475daff3d933b80.jpeg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n\n",            "readNum": "999",            "createTime": "2018-09-01 22:35:26.0",            "author": "小石头",            "classify": "零基础学小程序"        },        {            "aid": 6,            "title": "零基础学小程序007---小程序获取用户openid",            "content": "我们在做小程序支付,在区分小程序用户时都需要用到openid,用户openid就相当于用户在小程序里的身份证。做为用户的唯一标示,所以获取到用户openid就显得很重要了,今天来教大家怎么样获取要用户的唯一标示  **openid**\n所需参数     | 是否必需\n-------- | ---\nappid | 必需\nappsecret    | 必需\n\n还是先看效果图\n![获取openid.png](https://upload-images.jianshu.io/upload_images/6273713-70da703bb2d49674.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n上面就是我们实现后的效果。接下来开始给大家讲解具体实现步骤。\n### 一,先看小程序官方文档(官方文档才是最好的老师)\n![微信官方文档.png](https://upload-images.jianshu.io/upload_images/6273713-b0180afc6f602c45.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n官方文档已经说了,要先通过wx.login获取一个临时凭证code,然后我们拿这个code去自己的服务器换取用户openid。那么问题来了,我们需要有一个自己的服务器,并且支持https请求。是不是感觉很难,为了帮助大家尽快学习小程序开发,后台的问题我给大家解决。大家可以直接请求我的后台api接口就行,不用自己搭建后台。\n### 二,访问服务器获取openid\n不多说先上代码,讲代码是最快的学习方式\n- user.wxml\n```\n<button type='primary' bindtap='getOpenid'>获取用户openid</button>\n<text>{{openid}}</text>\n```\n- user.js\n```\n// pages/user/user.js\nPage({\n data: {\n  openid: ''\n },\n\n // 获取用户openid\n getOpenid: function() {\n  let that = this;\n  //获取openid不需要授权\n  wx.login({\n   success: function(res) {\n    //请求自己后台获取用户openid\n    wx.request({\n     url: 'https://30paotui.com/user/wechat',\n     data: {\n      appid: '你的小程序appid',\n      secret: '你的小程序secret',\n      code: res.code\n     },\n     success: function(response) {\n      var openid = response.data.openid;\n      console.log('请求获取openid:' + openid);\n      //可以把openid存到本地,方便以后调用\n      wx.setStorageSync('openid', openid);\n      that.setData({\n       openid: \"获取到的openid:\" + openid\n      })\n     }\n    })\n   }\n  })\n },\n})\n```\n注意点\n- 1,https://30paotui.com/user/wechat是用来获取openid的服务器接口。(免费提供给大家用)\n- 2,下面的apppid和appsecret到你的小程序后台去找,找到后替换到下面的地方\n```\ndata: {\n      appid: '你的小程序appid',\n      secret: '你的小程序secret',\n      code: res.code\n},\n```\n![获取appid和appsecret.png](https://upload-images.jianshu.io/upload_images/6273713-2aedcb68c7415e40.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n\n到这里就可以获取到用户的openid了,是不是很简单。\n扫描识别下面小程序码,学习更多零基础入门小程序的课程。\n![1编程学习.jpeg](https://upload-images.jianshu.io/upload_images/6273713-526d8edd8cf06fd7.jpeg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)\n",            "readNum": "888",            "createTime": "2018-09-07 17:15:57.0",            "author": "小石头",            "classify": "零基础学小程序"        }    ]}

可以看到我们一共获取到7条数据。我们先对每条数据做下说明

数据属性 说明
aid 文章id
title 文章标题
content 文章正文
readNum 阅读数
createTime 文章创建时间
author 文章作者名
classify 文章所属类别

知道了每个字段代表什么,我们接下来就可以做数据解析了。做数据解析之前要明白一点,我们的7条数据都是存在一个数组里面的。

小程序请求网络数据并填充到首页列表插图1
简单认识数组

比如我们想解析获取到数组里面的第一条数据

小程序请求网络数据并填充到首页列表插图2
解析第一条数据

二,填充网络数据到我们的首页列表

005解析本地数据到列表

还记得我们第5节里解析本地数据到列表吗,这里我们实现原理都一样,只不过这里换成把网络数据解析到列表。

小程序请求网络数据并填充到首页列表插图3
解析网络数据到首页列表

下图就是我们把网络数据填充到首页列表的效果

小程序请求网络数据并填充到首页列表插图4
效果图

三,css简单讲解

看上面的效果图可以看到我们的时间是红色的,背景是灰色的,还有一个紫色的分割线。我们在home.wxss设置样式

小程序请求网络数据并填充到首页列表插图5
设置样式

可以看到我们在home.wxml里有 class=”item-title”,这里的item-title就是class选择器。代表我们的标题。
我们对标题设置颜色和大小,只需要在home.wxss设置以下代码就可以了。

.item-title {  font-size: 1.3rem;  color: white;}

小程序请求网络数据并填充到首页列表插图6
css类选择器学习

css类选择器知识学习链接

到此我们今天的课就学完了,本节课有点长,需要大家多看几遍。更着老师思路走。

下面我把home.wxml,home.js,home.wxss三个文件贴出来

<!-- home.wxml --><!--列表渲染  --><block wx:for="{{dataList}}" wx:key="item"> <view class='item-container'>  <!--这里只是为了展示序列号  -->  <text>{{item.aid}}</text>  <!--这里展示标题 -->  <text class='item-title'> {{item.title}} </text>  <!--这里展示时间 -->  <text class='item-time'> {{item.createTime}} </text> </view></block>
// home.jsPage({ data: {}, //小程序的生命周期函数 onLoad() {  this.getHomeList(); //调用网络请求的方法:getHomeList }, //获取网络数据 getHomeList() {  let that=this;  wx.request({   url: "https://30paotui.com/article/list",   success: function(res) { //请求成功    //解析网络数据到首页列表    that.setData({     dataList: res.data.data    });   },   fail: function(res) { // 请求失败   }  }) }})
/* home.wxss *//* 列表布局   */.item-container {  padding: 25rpx;  background: gray;  flex-direction: row;  border-bottom: 1px solid rebeccapurple;}.item-title {  font-size: 1.3rem;  color: white;}.item-time{  font-size: 40rpx;  color: red;}

源码和视频讲解请加我微信,有问题也可以加我微信:2501902696(备注小程序)

文章转载于:https://www.jianshu.com/p/bf1c61b0d14b

原著是一个有趣的人,若有侵权,请通知删除

未经允许不得转载:起风网 » 小程序请求网络数据并填充到首页列表
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录