Example of WeChat mini-app ticket query and mini-app example

Source: Internet
Author: User

Example of ticket query by applet, and example of Applet

Simple Example of a applet-train ticket query application, learning to master the applet framework and implementation of development steps. Small programs are lightweight and easy-to-use. They are easy to learn and use.

1. Related Links

Get the address of this project code

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

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

Learning materials for applet Development

Developer platform: https://mp.weixin.qq.com/debug/wxadoc/dev/framework/config.html? T = 1475052055990. The mini-Program Development Tool can be downloaded from it. Fortunately, the new version no longer needs to be installed with version 0.7 for First Login, but can be directly logged on for development and debugging;

Flex css layout: it takes a long time to learn how to use layout. Otherwise, it is difficult to even layout the most basic components. Let alone design beautiful and interactive interfaces;

Mini: http://mp.weixin.qq.com/wiki? T = resource/res_main & id = mp1474632113_xQVCl & token = & lang = zh_CN, the content here can be said to be complementary to the content in the first link. Learn and use it;

2. Interface display

Use a dynamic graph to describe the current functions:

2.1 The user profile picture and user name are displayed in the upper part of the homepage (consistent with the information in the middle). These components are provided by the tool. We can modify these components and content, which will be mentioned later ); the lower part shows a classic greeting "Hello World" and provides a clickable button "click to get a train ticket ";

2.2 click the button and use the specified parameters (call the API for querying train tickets from Baidu APIStore, and set the parameters required for site-Site query to the origin site, destination, and time) send a network request to parse the obtained JSON data by train number as a node and display the basic information (except the detailed seat information) on the new page ), provide a clickable button "click to view seat information" for each vehicle trip ";

2.3 After clicking the seat query button in a vehicle trip, all the seat information corresponding to the trip will be displayed on the new page;

2.4 click the "return" button in the upper left corner of the last two pages to return to the previous page. This function is also provided by the tool;

By the way, insert an animation in the blog Garden. The demonstration process above is a gif image, just like adding a normal image. The recording tool uses an animated Gif recording tool to specify the recording information such as the Operation and region required when the recording starts or stops.

3. Key Points Analysis

The use of mini-program tools and the structure of the initial project are already rich in online resources, so I don't want to worry about it any more. For details, refer:

Next, let's talk about the points that I personally think are worth sharing and recording in the course of learning and development. We welcome everyone to discuss and correct them together, especially those that are wrong or need to be improved. The following is only the Code directly related to the points mentioned. The overall code can be viewed in the project. We recommend that you debug it yourself.

3.1 index

Index is automatically generated when the project is created. It is used as the startup page of the applet.

3.1.1 index. wxml

The Avatar and user name on the homepage can be seen from the demonstration process that I changed the name "***" 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"> User Name </text> <! -- {UserInfo. nickName} is directly written as "User Name" --> 4 </view>

The original username content is {userInfo. nickName }}, {key_name} is used to obtain the value corresponding to the keyword name key_name (the data is generally key_name: the value format is defined in the data member of the js file in the same directory of the wxml file, which will be explained later). The Avatar resource displayed by the image is also specified as src = "{userInfo. avatarUrl }}", the data generated in the program can be viewed in the AppData column at the top right of the developer tool.

If you do not need to obtain data from the js file, you can directly write data values like the "user name" in the Code. However, this is generally not recommended, because apps like Android put data values in strings during development. xml files are used to separate data from the layout. The layout and functions are separated to facilitate development and maintenance.

The class item in the component is used to set its style. The style information corresponding to the attribute name is defined in the wxss file. In addition to the style defined in the wxss file in this directory, you can also use the app. defined in the wxss file. If a style is only used on a page, we recommend that you define it in the wxss file under its directory, that is, within a local scope. If multiple pages are used together, that is, global styles, it is generally defined in the main app. wxss file. The class style can specify attributes such as the width and height of the component and the background color.

Add the "click to get train ticket" component at the bottom of the page:

1 <view class = "gettrain-button" bindtap = "getTrainInfo"> 2 <text> click to get a train ticket </text> 3 </view>

The purpose of the button is to allow users to click and interact. The button, text, or other components are used according to specific requirements. The text component is used here. The text content is directly written into the string "click to get a train ticket". For the layout of only one sub-component, the following code does not need to be nested, and the layout can be done at a layer. Generally, the fewer nested layers, the faster the loading speed, which is crucial to the mobile app experience.

1 <view class = "gettrain-button" bindtap = "getTrainInfo"> 2. Click get train ticket 3 </view>

However, if multiple child components under the parent container share their defined styles, the nested code can be much simpler:

1 <view class = "gettrain-button"> 2 <text bindtap = "getTrainInfo"> click get train ticket </text> 3 <text bindtap = "getCarInfo"> click get bus ticket </text> 4 <text bindtap = "getPlaneInfo"> click to get the plane ticket </text> 5 </view>

To enable click interaction, a component must bind an event response method to it. Common events include single-point -- bindtap, long-pressed -- binglongtap. Bindtap = "getTrainInfo". The text in double quotation marks is the method name. In the js file, define the method with this name and perform the necessary processing.

3.1.2 index. js

Implement the function of binding the button "click to get train ticket" in the wxml layout:

// GetTrainInfo: function () {wx. request ({url: 'http: // response, header: {apikey: '361cf2a2459552575b0e86e0f62302bc ',}, data: {version: '1. 0 ', from: 'beijing', to: 'hangzhou', date: '2017-11-15',}, success: function (res) {var json = res. data; // convert the JSON type to the String type for url parameter transmission. Otherwise, the value is [object Object object] var jsonString = JSON. stringify (json); wx. navigateTo ({url :' ../Train? TrainInfos = '+ jsonString ,});},});},

Let's take a look at the explanation of the network request Method-wx. request (OBJECT) on the applet Website:

In general, the method provided by the wx api has an Object parameter by default. If this parameter is required, it is input. If this parameter is not required, it is not input. However, this is not suitable for Android Developers like me at the beginning. How can I input a {...} when calling a function {...} parameters, each item in the Code is separated by a comma.

From the Code, when initiating a network request, four parameters listed in the figure are passed in: url, header, data, and success. The parameters passed in vary with requirements. For the wx. request method, the first four parameters: url, header, data, and method must be transmitted according to the network request target.

In this case, the use of Baidu APIStore to which network train tickets to get station-station Train ticket information (http://apistore.baidu.com/apiworks/servicedetail/697.html), the official website of the interface to call the parameter information and format is as follows:

 

By combining the information in the above two figures, the parameters correspond one to one:

Wx url -- Address of the train ticket query interface;

Header -- Request Parameter header;

Data -- Request Parameter urlParam;

Method -- Request method;

The method parameter in wx is GET by default, which is the same as that specified by the train ticket query interface. Therefore, this parameter can be omitted during call.

For the last three callback functions: success, fail, And comlete, success is added to the Code to process the data when the request is successful. Of course, the general program must handle the request failure. Next we will analyze the code in the success method, including JSON data conversion and new page Jump. The data returned by the request is transmitted to the function in the form of the res parameter. First, let's take a look at the information contained in res. You can print it in the console item on the tool debugging page through the Code Console. log (res.

 

Request -- OK and statusCode -- 200 indicate that the request is successful, so the success method is called back. The data object is the data we need. More precisely, the data. data. trainList object is the real train ticket information.

Var json = res. data, get the data object (the data returned by network requests is generally in JSON format), and assign it to the variable json;

Var jsonString = JSON. stringify (json) converts a JSON-type object to a String type for transmission as a url parameter. It has been delayed for a long time at the beginning, if data is directly transmitted without conversion, the desired data cannot be obtained on the target page. The reasons are described below;

Url: '../train? TrainInfos = '+ jsonString, jump to the corresponding page through the information specified by the url. If no additional parameters are required, directly write the url :'.. /train/train'; if you just pass a simple value, you can write it as url :'.. /train? Param = 123 ';

Now, if there is no network problem, click the button to query the train ticket and bring the result data to the new page.

3.2 train

Train is a custom New Page used to display basic information about train tickets. Note that the newly added page must be configured in the app. json file.

1 "pages/train", // train ticket information page
2 "pages/seat" // times remaining ticket information page

3.2.1 train. wxml

Because the Origin Site and the terminal station of all train tickets are the same, such as Beijing-East Hangzhou, the site information is displayed at the top of the page:

1 <text class = "train-item"> departure location: {trainList [0]. from }}</text>
2 <text class = "train-item"> destination: {trainList [0]. to }}</text>

The trainList object is defined as a data member in the js file, and the value is the JSON object-trainList In the last figure above, that is, the train ticket train number array. Each element contains the specific information of a train number.

Next, we will display the information of each vehicle, separated by a horizontal line (for the purpose of learning and testing, we have not worked hard on the beautiful layout. Sorry, everyone ):

1 <view class = "line"> </view> 2 <block wx: for = "{trainList}" wx: for-item = "train"> 3 <text class = "train-item" >{{ index + 1 }}. vehicle count: {train. trainNo }}</text> 4 <text class = "train-item"> model: {train. trainType }}</text> 5 <text class = "train-item"> Start Time: {train. startTime }}</text> 6 <text class = "train-item"> arrival time: {train. endTime }}</text> 7 <text class = "train-item"> total duration: {train. duration }}</text> 8 <view id = "trainindex-{index}" class = "getseat-button" bindtap = "getSeatInfo"> 9 <text> click to view Details seat Information </text> 10 </view> 11 <view class = "line"> </view> 12 </block>

Lines 1st and 11 are very simple. Add a horizontal line between the site and the train count, the train count and the train count.

When the number of components in the layout is related to the data in js, that is, when writing dead components in wxml cannot meet the requirements, you can use block and wx: for dynamic component generation.

Row 2nd wx: for = "{trainList}" indicates that components in the block can use the content in the array trainList to iterate from the subscript 0. There are several elements in the data, several sets of components are dynamically generated. Wx: for-item = "train" specifies that the element name in the array is train (the default is item, one of the meanings of which is high readability). You can use train to obtain the attribute value later. key_name format.

The component is added at the beginning of Line 1. The type is text and the value is {index + 1 }}. vehicle count: {train. trainNo }}, the first half is used to indicate the serial number of each vehicle entry, starting from 1. The index and item are similar to the default iterative index name, which is actually the current subscript of the array element, starts from 0.

The text Component added in the following lines is similar to that in the second line, but there are two points in the second line:

* 1 bindtap = "getSeatInfo": bind a callback function. When you click it, the new page is displayed, showing the seat information of the current vehicle count;

* 2 id = "trainindex-{index}", specify an id for the component. You can see that this attribute has not been set for the previous component (you can leave this attribute unneeded ), so when will it be necessary? In one case, when the callback method bound to a component in js needs to know which component triggers itself, such as the method getSeatInfo In the first point, to display the corresponding seat information after clicking the view seat information button for a vehicle trip, you need to know the subscripts of the trainList array corresponding to the component, it can be implemented by using the id and index attributes;

3.2.2 train. js

First, define the data member trainList to receive the data transmitted from the index page:

TrainList: []

If data needs to be loaded when the page is started, you must add the onLoad method (automatically run at the beginning to load and process the data in it). Otherwise, you can leave it empty.

1 onLoad: function (options) {2 var jsonString = options. trainInfos; 3 // convert string type to JSON type 4 var json = JSON. parse (jsonString); 5 this. setData ({6 trainList: json. data. trainList, 7}); 8 },

When the method caller has parameter data transmission, we can get it by adding method parameters. For parameter names, the automatic start method is generally options, and the component callback method is generally e (event ).

Row 3 obtains the train ticket information parameter trainInfos passed in when the train page is opened on the index page.

The String type object in line 4th is converted back to the JSON format. As mentioned on the index page, url-based parameters are String types converted from JSON objects.

The row 6th retrieves the real train ticket information array and assigns it to the data member trainList.

Note: When assigning values to data members, you must call the setData method of the page itself. Otherwise, the value is not synchronized to the wxml file even if it is assigned. This is prone to errors and is difficult to identify the cause.

After the vehicle number array is obtained, the wxml file displays the corresponding information based on the Component Property settings. Next, let's look at the callback method corresponding to the "click to view seat information" button:

1 getSeatInfo: function (e) {2 var prefix = 'trainindex-'; 3 var trainindex = e. currentTarget. id. substring (prefix. length); 4 // output the ticket index obtained based on the component id, used to display detailed seat Information 5 console. log (trainIndex); 6 var trainNo = this. data. trainList [trainIndex]. trainNo; 7 var json = this. data. trainList [trainIndex]. seatInfos; 8 // convert the JSON type to the String type for url parameter transmission. Otherwise, it will become [object Object] After transmission, and pass the carriage call 9 var jsonString = JSON. stringify (json); 10 w X. navigateTo ({11 url: '../seat? '+ 'Trainno =' + trainNo + '& seatInfos =' + jsonString, 12}); 13 },

Rows 2nd and 3 get the index part of the previously defined component id, that is, click the subscript of the trainList array corresponding to the component. Of course, you can not add the prefix 'trainindex-'in the original definition to ensure readability, because there is always a clear identifier when the project grows.

Lines 6th and 7 obtain the train number and seat information of the trains respectively. They will be passed to the seat page later.

Line 9th first converts the obtained JSON format object to the String type so that it can be correctly transmitted as a parameter in the url.

The second line opens a new page where seat displays the seat information. Multiple parameters are separated by the "&" symbol.

3.2.3 train. json

In addition to the page for configuring the onLoad method, the app. json file in the main program also specifies some global window styles. If a page does not have a local window attribute defined in its own json file, or there is no json file at all, global is used by default.

The project initially did not generate a json file for index, because it serves as the startup page and uses the Global "WeChat" directly. In fact, the index title should be the name of the applet, the program we actually developed must have another name.

As you can see, logs, train, and seat all define the title, and the result will overwrite the global value. Taking train as an example, it is defined in the json file as "station-station train Query Information ":

1 {2 "navigationBarTitleText": "station-station Train Query Information" 3}

Another point is that the page json file does not need or can not configure the page attributes (Pages). You can only set the window attributes, so you can omit the window name and use {...} directly like the above Code {...} format.

Seat 3.3

The seat page is used to display the seat information of a vehicle trip, including the seat level, fare, and remaining ticket. Through the analysis of the train page, I believe that everyone is familiar with the transmission of network requests and data between pages, wxml and js files. The seat and train are similar, and there is nothing special, so we will not talk about anything here like logs.

4. insights

The access port of the applet is unknown, but it should be different from the subscription number, service number, and enterprise number. Search is enabled and used up, and closed once used up. There is no mobile app installation or download process. features such as high traffic, light weight, and ease of use are their advantages. However, due to this advantage, developers are worried that this may make small programs not as powerful as the app, after all, unknown factors such as access ports, review mechanisms, promotion costs, and maximum allowable memory are crucial to a single application.

For beginners (such as android development), no matter what is mentioned above, while figuring out the application requirements, you must start learning the front-end knowledge quickly.

Thank you for reading this article. I hope it will help you. Thank you for your support for this site!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.