Home  >  Article  >  WeChat Applet  >  WeChat mini program train ticket inquiry code

WeChat mini program train ticket inquiry code

不言
不言Original
2018-06-23 11:56:582388browse

This article mainly introduces relevant information on the WeChat mini program train ticket query example. Here is a simple example to illustrate the framework of the WeChat mini program and how to develop it. Friends in need can refer to it

WeChat A simple example of a mini program - train ticket query application, learn to master the mini program framework, and implement the development steps. The WeChat mini program embodies the characteristics of being light and easy to use, and it is quick to get started, and the front-end knowledge is easy to learn and use.

1. Related links

Get the project code address

Github: https://github.com/VincentWYJ/WXAppTrain.git;

Blog file: http://files.cnblogs.com/files/tgyf/WXAppTrain.rar;

WeChat applet development learning materials

WeChat Developer Platform: https://mp.weixin.qq.com/debug/wxadoc/dev/framework/config.html?t=1475052055990. Mini program development tools can be downloaded there. Fortunately, the new version is no longer available. You need to install version 0.7 to log in first, but you can log in directly to develop and debug;

Flex css layout: http://www.w3cplus.com/css3/flexbox-basics.html, like me Such non-front-end developers must first spend time learning how to use Flex layout, otherwise it will be difficult to even lay out the most basic components, let alone design a beautiful and interactive interface;

Mini program: http://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1474632113_xQVCl&token=&lang=zh_CN. If you click the prompt and it cannot be opened/return to the homepage, please copy and paste it into the address bar to open it. Here is The content can be said to complement the content in the first link, so use it while learning;

2. Interface display

Describe the current implementation with dynamic graphics Function:

2.1 The upper part of the home page displays the user's avatar and user name (the same as the information in WeChat. This part of the component comes with the tool. We can modify this part of the component and content, which will be mentioned later. ); The lower part displays a classic greeting "Hello World" and provides a clickable button "Click to get a train ticket";

2.2 After clicking the button, the Baidu APIStore is called through the pre-specified parameters ( Zhongqunar.com train ticket query interface, the required parameters for station-to-station query are origin, destination and time) send a network request, parse the obtained JSON data according to the train number for the node and display the basic information on the new page (In addition to detailed seat information), a clickable button "Click to view seat information" is provided for each train;

2.3 After clicking the seat query button in a certain train, all seat information corresponding to the train will be Displayed in a new page;

2.4 Click the "Return" button in the upper left corner of the next two pages to return to the previous page. This function is also built-in with the tool;

By the way, in Insert animation into the blog garden. The above demonstration process is a picture in gif format. You can operate it just like adding a normal picture. The recording tool uses Lingzhe Gif recording, which allows you to specify recording information such as required operations and areas when starting and stopping.

3. Key points analysis

Regarding the use of WeChat mini program tools and the structural description of the initial project, there are already abundant online resources, so I won’t go into details here. If you want to know more, you can refer to:

Now I will start to talk about the points that I personally think are worth sharing and recording in the learning and development process. I welcome everyone to discuss and correct me, especially the things that are wrong or need to be improved. . Only the code directly related to the points mentioned is given below. The overall code can be viewed in the project project. It is recommended that you debug it yourself.

3.1 index

index is automatically generated when the project is created and serves as the startup page of the mini program.

3.1.1 index.wxml

The avatar and user name on the homepage. From the demonstration process in the above picture, you can see that I changed the name of WeChat "***" to "user name" ”:

1 <view bindtap="bindViewTap" class="userinfo">
2   <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>
3   <text class="userinfo-nickname">用户名</text> <!-- {{userInfo.nickName}}直接写成“用户名” -->
4 </view>

The original content of the user name part is {{userInfo.nickName}}, and the function of {{key_name}} is to obtain the keyword name key_name The corresponding value (data is generally defined in the data member of the js file in the same directory as the wxml file in the form of key_name:value, which will be explained later). The avatar resource displayed by the image is also specified in this way as src="{{userInfo. avatarUrl}}", the data generated in the program can be viewed in the AppData column on the top right of the developer tools.

If you do not need to obtain data from the js file, you can directly write the data value like the "user name" in the code. However, this is generally not recommended because platform apps such as Android will The purpose of putting data values ​​into files such as strings.xml is to separate data from layout, and to achieve code separation between layout and functions to facilitate development and maintenance.

组件中的class项用来设置其样式,属性名对应的样式信息定义在wxss文件中,除了可以使用定义在本目录wxss文件中的样式,还可以使用app.wxss文件中定义的。如果样式只是在某页面中使用,那么建议定义在其目录下的wxss文件中,即局部作用域内;如果是多个页面共同使用,即全局样式,那么一般定义在主程序app.wxss文件中。class样式可以指定组件的宽高、背景颜色等属性,本文不再进行详述。

在界面下方添加按钮“点击获取火车票”组件:

1 <view class="gettrain-button" bindtap="getTrainInfo">
2   <text>点击获取火车票</text>
3 </view>

按钮的目标是为了让用户可以点击进行交互,至于使用button、text或其他组件,视具体需求而定。这里是利用text组件,文本内容直接写入了字串“点击获取火车票”,对于只有一个子组件的布局其实可以如下面代码不用嵌套,一层布局搞定。一般来说嵌套层数越少,加载速度越快,这对移动程序的体验是至关重要的。

1 <view class="gettrain-button" bindtap="getTrainInfo">
2   点击获取火车票
3 </view>

但如果在父容器下有多个子组件共享其定义的样式,那么嵌套可以另代码简洁很多:

1 <view class="gettrain-button">
2   <text bindtap="getTrainInfo">点击获取火车票</text>
3   <text bindtap="getCarInfo">点击获取汽车票</text>
4   <text bindtap="getPlaneInfo">点击获取飞机票</text>
5 </view>

组件若要有点击交互功能,须为其绑定事件响应方法,常用的有单点--bindtap,长按--binglongtap。bindtap="getTrainInfo",双引号中的文本是方法名称,在js文件中以该名定义方法,做需要的处理即可。

3.1.2 index.js

 实现wxml布局中按钮“点击获取火车票”绑定的函数功能:

//获取火车票函数
getTrainInfo: function() {
 wx.request({
  url: &#39;http://apis.baidu.com/qunar/qunar_train_service/s2ssearch&#39;,
  header: {
   apikey: &#39;361cf2a2459552575b0e86e0f62302bc&#39;,
  },
  data: {
   version: &#39;1.0&#39;,
   from: &#39;北京&#39;,
   to: &#39;杭州&#39;,
   date: &#39;2016-11-15&#39;,
  },
  success: function(res) {
   var json = res.data;
   //将JSON类型转为String类型用以url参数传递,否则传递后会变成[object Object]
   var jsonString = JSON.stringify(json);
   wx.navigateTo({
    url: &#39;../train/train?trainInfos=&#39;+jsonString,
   });
  },
 });
},

我们先来看看微信小程序官网对于网络请求方法--wx.request(OBJECT)的说明:

  一般来说,wx api提供的方法默认会有一个Object参数,需要时传入,不需要时不传便是。不过这对于像我这种Android开发者来说一开始有点不适应,怎么函数调用时都传入一个{...}参数,内部各个项之间用逗号“,”分隔,代码中的url、data等。

从代码中看,发起网络请求时传入了图中列出的四项参数:url、header、data及success,不同需求传入的参数也会不同。对于wx.request方法而言,需根据网络请求目标来传参数的是前四项:url、header、data及method。

以本案例利用百度APIStore去哪网火车票获取站--站火车票信息来说(http://apistore.baidu.com/apiworks/servicedetail/697.html),其官网给出的接口调用的参数信息与格式如下:

 

将上面两张图中的信息结合起来看,参数是一一对应的:

wx url——火车票查询 接口地址;

header——请求参数header;

data——请求参数urlParam;

method——请求方法;

因为wx中的method参数默认是GET,和火车票查询接口指定的一致,所以调用时可以省略。

而对于最后三个回调函数:success、fail及comlete,代码中添加了success,在请求成功时对数据进行处理。当然,一般的程序还得对请求失败的情况做处理。下面就来分析success方法中的代码,包括JSON数据的转换与新页面的跳转,请求返回的数据以参数res的形式传入到function中。先来看看res中包含了哪些信息,通过代码console.log(res)可以将其打印在工具调试页面的Console项中。

 

request--ok和statusCode--200表示请求成功,所以才会回调success方法。而data对象才是我们需要的数据,更精确地说,data.data.trainList对象才是真正的火车票信息。

var json = res.data,获取data对象(网络请求返回的数据一般为JSON格式),赋给变量json;

var jsonString = JSON.stringify(json),将JSON类型对象暂时转换为String类型,用来作为url的参数部分进行传递;一开始在这里耽搁了很久,不进行转换直接传的话在目标页面获取不到想要的数据,下面会说明原因;

url: '../train/train?trainInfos='+jsonString,通过url指定的信息跳转到对应页面,如果不需要额外参数,直接写url: '../train/train';如果只是传递简单的值,可写成url: '../train/train?param=123';

至此,如果网络没有问题,点击按钮便可以进行火车票的查询并携带结果数据跳转到新页面了。

3.2 train

train是自定义新建的页面,用来显示火车票基本信息,注意新添的页面需在app.json文件中进行配置。

1 "pages/train/train",  //火车票车次信息页面
2 "pages/seat/seat"  //车次余票信息页面

3.2.1 train.wxml

由于站--站火车票所有车次的始发站和终点站是一样,如北京--杭州东,所以先在页面顶部显示站点信息:

1 e9cac1a30ddd806ef649c40166e75c78出发地:{{trainList[0].from}}273e21371c5d5e701d3c98517a0bfa41
2 e9cac1a30ddd806ef649c40166e75c78目的地:{{trainList[0].to}}273e21371c5d5e701d3c98517a0bfa41

trainList对象会在js文件中定义成data成员,值为上面最后一张图中的JSON对象--trainList,即火车票车次数组,每个元素包含一个车次的具体信息。

接下来显示每个车次的信息,以横线作分隔(由于是以学习和测试为目的,所以就没有在布局的美观上下功夫,大家见谅):

 1 <view class="line"></view>
 2 <block wx:for="{{trainList}}" wx:for-item="train">
 3  <text class="train-item">{{index+1}}. 车次:{{train.trainNo}}</text>
 4  <text class="train-item">车型:{{train.trainType}}</text>
 5  <text class="train-item">起始时间:{{train.startTime}}</text>
 6  <text class="train-item">到站时间:{{train.endTime}}</text>
 7  <text class="train-item">总时长:{{train.duration}}</text>
 8  <view id="trainindex-{{index}}" class="getseat-button" bindtap="getSeatInfo">
 9   <text>点击查看座位信息</text>
10  </view>
11  <view class="line"></view>
12 </block>

第1、11行很简单,在站点与车次、车次与车次之间添加横线。

当布局中的组件个数和js中的数据有关,即在wxml中写死组件不能满足需求时,可以利用block和wx:for来进行组件的动态生成。

第2行wx:for="{{trainList}}"表示block块中的组件可以使用数组trainList中的内容,从下标0开始迭代,数据中有几个元素,就会动态生成几套组件。wx:for-item="train"指定数组中元素的名称为train(默认的是item,指定的意义之一是可读性强),后续获取属性值时可通过train.key_name的形式。

第3行开始添加组件,类型是text,值为{{index+1}}. 车次:{{train.trainNo}},前半部分用来标明每个车次的序号,从1开始;而index和item类似,是默认的迭代索引名称,其实就是数组元素当前的下标,从0开始。

后面几行添加text组件和第3行差不多,但第8行有两个点说一下:

*1 bindtap="getSeatInfo",绑定一个回调函数,点击时跳转到新页面,显示当前车次对应的座位信息;

*2 id="trainindex-{{index}}",给组件指定id,可以看到之前的组件都没有设置过该属性(不需要就可以不设置),那么什么时候需要呢?其中一种情况,当js中某组件绑定的回调方法需要得知是哪个组件触发了自己的时候,比如第一点中的方法getSeatInfo,要想点击某车次的查看座位信息按钮后显示出对应的座位信息,就得知道点击组件对应的trainList数组下标,而这个需求,正好可以借助id和index属性来实现;

3.2.2 train.js

首先定义data成员trainList,用来接收index页面传递过来的数据:

trainList: []

页面启动时若有数据需要载入,那么得添加onLoad方法(一开始自动运行,在其中实现数据的加载与处理),否则可以不添加。

1 onLoad: function(options) {
2   var jsonString = options.trainInfos;
3   //将字串类型转为JSON类型
4   var json = JSON.parse(jsonString);
5   this.setData({
6    trainList: json.data.trainList,
7   });
8 },

当方法的调用者有参数传入时,我们可以通过添加方法参数的形式来获取。对于参数名,自动启方法一般为options,组件回调方法一般为e(event)。

第2行获取index页面在打开train页面时传入的火车票信息参数trainInfos。

第4行将String类型对象转换回JSON格式,之前在index页面提到过,url传的参数是由JSON格式对象转换过来的String类型。

第6行将真正的火车票车次信息数组取出,赋给数据成员trainList。

注意:给数据成员赋值时,必须调用页面自身的setData方法,否则就算赋值了也不会同步到wxml文件中去,这一点容易出错且不好定位原因。

车次数组得到后,wxml文件就会根据组件的属性设置显示对应的信息。再来看实现按钮“点击查看座位信息”对应的回调方法:

1 getSeatInfo: function(e) {
 2  var prefix = &#39;trainindex-&#39;;
 3  var trainIndex = e.currentTarget.id.substring(prefix.length);
 4  //输出根据组件id获取的车票索引,用以显示详细的座位信息
 5  console.log(trainIndex);
 6  var trainNo = this.data.trainList[trainIndex].trainNo;
 7  var json = this.data.trainList[trainIndex].seatInfos;
 8  //将JSON类型转为String类型用以url参数传递,否则传递后会变成[object Object],同时传递车次
 9  var jsonString = JSON.stringify(json);
10  wx.navigateTo({
11   url: &#39;../seat/seat?&#39;+&#39;trainNo=&#39;+trainNo+&#39;&seatInfos=&#39;+jsonString,
12  });
13 },

第2、3行获取之前定义的组件id中的index部分,即点击组件对应的trainList数组的下标。当然原先定义时也可以不添加前缀'trainindex-',完全是为了可读性,因为当项目越来越大时有个一目了然的标示总是不错的。

第6、7行分别获取车次信息的列车号与座位信息,他们稍候会被传递到seat页面。

第9行同样地将得到的JSON格式对象先转换为String类型,让其可以在url中作为可被正确传递的参数。

第11行打开新的页面seat显示座位信息,多个参数之间以“&”符号分隔。

3.2.3 train.json

主程序中app.json文件除了配置需要调用onLoad方法的页面外,还指定了一些全局的window样式。若某个页面在自己的json文件中没有定义局部的window属性,或根本没有json文件,那默认将使用全局的。

项目初始没有为index生成json文件,因为其作为启动页,直接用全局的“WeChat”就好,其实index标题应该是小程序的名称,我们自己真正开发的程序肯定得取另一个名字。

可以看到,logs、train及seat都对标题进行了定义,结果就是会覆盖掉全局的值。以train为例,其在json文件中定义标题为“站-站火车查询信息”:

1 {
2   "navigationBarTitleText": "站-站火车查询信息"
3 }

还有一点,页面的json文件不需要也不能页面配置属性(Pages),只能设置window属性,所以就可以省略window名称,直接像上述代码用{...}形式即可。

3.3 seat

seat页面用来显示某车次的座位信息,包括座位等级、票价及余票。通过train页面的分析,相信大家对网络请求,数据在页面与页面、wxml与js文件之间的传递渐渐熟悉了。而seat和train类似,没有什么特别的地方,所以和logs一样这里就不再讲什么了。

4. 小感悟

 微信小程序,虽然目前还不知道其在微信的接入口,但应该和订阅号、服务号以及企业号会有所不同。搜索打开使用,用完关闭,没有移动app的安装、下载等过程,微信流量大,轻便、易用等特性是其优点。然而正是因为这个优点,开发者担心这有可能使得小程序不能够像app那样强大,毕竟接入口、审核机制、推广成本以及最大允许内存等这些还未确定的因素对一款应来说都是至关重要的。

对于初学者(如原先搞android开发),暂且不管上面提到的那些,在弄明白应用需求的同时,得迈开并加快对前端知识学习的脚步了。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

微信小程序多张图片上传功能的实现

关于微信小程序进行微信支付的步骤

如何通过微信小程序获取用户手机号

The above is the detailed content of WeChat mini program train ticket inquiry code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn