Detailed description of how to add, delete, modify, and query instance code in WeChat applets

Source: Internet
Author: User
This article mainly introduces detailed information about adding, deleting, modifying, and querying operation instances for small programs. the instance code is attached here, for more information about how to add, delete, modify, and query instances for small programs, see this article. the instance code is attached here. For more information, see

Detailed description of adding, deleting, modifying, and querying operation instances for applets

1. add, delete, modify, and query the shipping address as an example

2. file directory

  1. Js files are logical control, mainly because they send requests and receive data,

  2. Json is used for local configuration on this page and overwrites the global app. json configuration,

  3. Wxss is used for page style settings,

  4. Wxml is a page, which is equivalent to html

 

The front-end page displays a form and existing receiver information.

1. several key points need to be understood.

A. Form, which requires binding a submit event. in the applet, the attribute is bindsubmit,

Bindsubmit = "formSubmit" The value formSubmit can be named as any conforming value, which is equivalent to onsubmit = "formSubmit ()" in the previous html, which is a function name, the formSubmit function event is triggered when a request is submitted. This function is written in js.

B. other attributes are similar to the previous HTML. Note that the form must have name = "value", and the backend processing is the same as before, for example, you can use $ _ POST ['username'] to receive "name =" username "PHP.

C. because the applet does not have the input submit button, each form must have a submit button,

RegisterThis button is used to enable event submission.

As for the loop, unpack it.

D. The applet gives us an encapsulated method onLoad: function (). This method is called when the page is loaded.

Var app = getApp () Page ({data :{}, onLoad: function () {var that = this; // receiving address homepage wx. request ({// The unique user id is missing. now there is a false id in the server controller = 2 url: 'https: // shop.yunapply.com/home/shipping/index', method: 'GET', data: {}, header: {'accept': 'application/json'}, success: function (res) {that. setData ({"addressInfo": res.data.info,}) console. log (res.data.info) ;}, fail: function () {wx. showToast ({title: 'server network error! ', Icon: 'Loading', duration: 1500 })}})}})

Query

Home page of the shipping address, used to pull the existing shipping address of the current user

var that = this;

I don't know why I want to do this. it may be to avoid this conflict or the semantics is unclear. I will assign the current object to the variable that

Wx. request ({}) initiates an https request

Url: 'https: // shop.com/home/shipping/index', the requested network interface

Method: 'GET', request method. the default value is GET. it must be declared during POST.

Data: {}, the data of the request sent

Header :{}, the sent header information,

The GET header information is: 'accept': 'application/json'

POST header information: "Content-Type": "application/x-www-form-urlencoded"

Success: Method for successfully calling a function () request

Fail: Method for calling failed function () requests

success: function(res) {    that.setData({      "addressInfo": res.data.info,    })   },

Res indicates the data returned by the server after the call is successful,

That. setData ({"addressInfo": res.data.info,}) add data to the data object on the current page. The key name is addressInfo and the key value is the returned data, what I need is all information of info Object of res data object

Fail: function () {wx. showToast ({title: 'server network error! ', Icon: 'Loading', duration: 1500 })}

Network request failure call method

ShowToast is similar to alert in JS. in the pop-up box, title is the information displayed in the pop-up box, and icon is the icon status in the pop-up box. Currently, only loading and success are available. Duration is the time when the pop-up box is displayed on the screen.

A. the url is the url you requested. for example, in the front-end, the action in the POST form is 'index. php', index here. php is the relative path, and the URL requested by the applet must be the absolute path of the network.

B. 'https: // shop.yunapply.com/home/shipping/index'. use the getmethod to request shippingcontrol under home‑owned

C. add the obtained value to data.

Check the index method under Shipping control in the HOME module.

Public function index () {// $ id is the user name id, and can be obtained through token or session (id) $ use_id = 2; $ res = D ('shipping ') -> getAddress ($ use_id); if ($ res = false) {$ this-> error ('No shipping address temporarily ', '', true );} else {$ this-> success ($ res, '', true );}}

View the getAddress () method in the Shipping model

/*** Get shipping address information * @ param $ id current user id * @ return all user addresses */public function getAddress ($ id) {$ address_list = $ this-> where (array ('User _ id' => $ id)-> select (); if ($ address_list = false) {return false;} return $ address_list ;}

In this way, the corresponding JSON data is returned based on whether the user has an address.

The JSON data in this example is

{"info":[{"id":"4","user_id":"2","name":"addTest","mobile":"15162550544","province":"","city":"","district":"","address":"44563","createtime":"2017-01-10 18:45:27","modifytime":"2017-01-10 18:45:27","default":"0"}],"status":1,"url":""}

After the request is successful, add JSON to data {} and set the key value to addressInfo.

The following information is displayed on the front-end page.

 
  
   
   
    
     
      
Shipping address {item. address }}
     
     
      
1 km
     
    
    
     
Consignee {item. name }}
    
    
     
Recipient's phone number {item. mobile }}
    
    
     
Delete
    
    
     
Edit
    
   
  
 

Control attribute wx: for binds an array, that is, the addressInfo array in JS. by default, the subscript variable name of the current item in the array is index by default, and the variable name of the current item in the array is item by default. According to {item. address }}, {item. name }}, {item. mobile }}, {item. id} the address, receiver, phone number, and id of the current data.

After the loop, all the address information can be displayed in the format, which is equivalent to foreach in the TP template.

Delete

You can see such a tag in the cyclic data of the foreground template.

Event. currentTarget. dataset. deleteid; indicates the data-* value of the target of the event object.

The bindtap attribute is bound to a click event on the template page. deleteClick is the method name of the trigger time.

In index. js, the deletion code is as follows:

// Delete the address deleteClick: function (event) {var id = event. currentTarget. dataset. deleteid; wx. request ({url: 'https: // shop.yunapply.com/home/shipping/delAddress? Id = '+ id, data :{}, method: 'GET', success: function (res) {if (res. data. status = 0) {wx. showToast ({title: res.data.info, icon: 'Loading', duration: 1500})} else {wx. showToast ({title: res.data.info, icon: 'Success ', duration: 1000}) // after deletion, a page should be refreshed, and other page refresh jumps together}, fail: function () {wx. showToast ({title: 'server network error! ', Icon: 'Loading', duration: 1500 })}})}

When you click the delete button at the front end, the deleteClick event is triggered. you can input a parameter to represent the Event object.

Event. currentTarget. dataset. deleteid; indicates the data-* value of the target of the event object.

Then pass in the url through GET. The delete function on the server side is as follows:

Public function delAddress ($ id) {$ res = D ('shipping')-> where (array ('id' => $ id)-> delete (); if ($ res) {$ this-> success ('deletion successfully', '', true);} else {$ this-> error ('deletion failed ','', true );}}

Based on the returned JSON value, the system prompts whether the deletion is successful or not.

Add and modify

Previously, I thought adding and modifying would be as simple as submitting a form, but I still thought it was different. I should write it again.

First, view the foreground form

 

A. Form, which requires binding a submit event. in the applet, the attribute is bindsubmit,

Bindsubmit = "formSubmit" The value formSubmit can be named as any conforming value, which is equivalent to onsubmit = "formSubmit ()" in the previous html, which is a function name, the formSubmit function event is triggered when a request is submitted. This function is written in js.

B. other attributes are similar to the previous HTML. Note that the form must have name = "value", and the backend processing is the same as before, for example, you can use $ _ POST ['username'] to receive "name =" username "PHP.

C. because the applet does not have the input submit button, each form must have a submit button,

RegisterThis button is used to enable event submission.

D. because both the add and edit addresses are on the same page, I need to add a default variable to each form. when I click modify, the default value is displayed in the input box.

E. There is an edit in the form and the event editClick is bound. when you click this button, the edit mode is displayed.

Add and modify data in a function, but the display of modified data is another function.

Modify it first. when you click edit, the editClick event is triggered.

JS:

EditClick: function (event) {var that = this; var id = event. currentTarget. dataset. editid; wx. request ({url: 'https: // shop.yunapply.com/home/shipping/edit? Id = '+ id, data :{}, method: 'GET', success: function (res) {if (res. data. status = 0) {wx. showToast ({title: res.data.info, icon: 'Loading', duration: 1500})} else {that. setData ({"addressEdit": res.data.info,}) }}, fail: function () {wx. showToast ({title: 'server network error! ', Icon: 'Loading', duration: 1500 })}})},

Paste a graph for better understanding

There is a Save button at the bottom. when you click edit, the editClick: function (event) is triggered. This event is the object of the currently triggered event,

Var id = event. currentTarget. dataset. editid; is used to obtain the editid value in the dataset of the current event object. the id here is the id of the current address.

Url: 'https: // shop.com/home/shipping/edit? Id = '+ id

Wx. request url, which places the id value on the url and passes it to the server as the GET parameter.

Data: {}, which is the data to be transferred.

Method: 'get' indicates the data transmission method. the default value is "GET ".

Data: {mobile: e. detail. value. mobile, password: e. detail. value. password },

The data here is the data sent by POST to the server in the form of {name: value}

Success: function () is an event when the request status is successfully triggered, that is, 200. Note that a successful request is not a successful operation. the request is only sent to the server.

Fail: function () is an event triggered when the network request fails.

The code here is related to the PHP backend program. The specific process is as follows,

1. GET

2. the backend PHP code is as follows:

Controller ShippingController. class. php

public function edit($id){  $res = D('Shipping')->find($id);  $this->success($res,'',true);}

That is to say, there is nothing to say about retrieving this data.

 that.setData({       "addressEdit": res.data.info,     })    }

After the request is successful, call the setData method of the applet, put the information returned by the server in addressEdit [], and then call {addressEdit on the front-end page. id }}, {addressEdit. name }}, {addressEdit. mobile }}, {addressEdit. address} displays the data, which is the operation for modification.

The next step is to submit the form.

The Js code is as follows:

AddSubmit: function (e) {if (e. detail. value. mobile. length = 0 | e. detail. value. name. length = 0 | e. detail. value. address. length = 0) {wx. showToast ({title: 'All receiver information cannot be blank! ', Icon: 'Loading', duration: 1500})} else if (e. detail. value. mobile. length! = 11) {wx. showToast ({title: 'Enter the 11-digit mobile phone number! ', Icon: 'Loading', duration: 1500})} else {wx. request ({url :' https://shop.yunapply.com/home/shipping/save ', Header: {"Content-Type": "application/x-www-form-urlencoded"}, method: "POST", data: {id: e. detail. value. id, mobile: e. detail. value. mobile, name: e. detail. value. name, address: e. detail. value. address}, success: function (res) {if (res. data. status = 0) {wx. showToast ({title: res.data.info, icon: 'Loading', duration: 1500})} else {wx. showToast ({title: res.data.info, icon: 'success', duration: 1000}) s EtTimeout (function () {wx. navigateTo ({url :'.. /address/index'})}, 1000) }}, fail: function () {wx. showToast ({title: 'server network error! ', Icon: 'Loading', duration: 1500 })}})}}

In the FORM at the front end, when you click the formtype = "submit" button, the addSubmit event is triggered. all the preceding if statements are for JS verification to prevent users from entering information.

1. Other requests are similar. find several different requests.

url: 'https://shop.yunapply.com/home/shipping/save',

Call the save method on the server

  header: {     "Content-Type": "application/x-www-form-urlencoded"    },

Because the POST and GET methods are different for data transmission, the POST header must be

"Content-Type": "application/x-www-form-urlencoded"

The GET header can be 'accept': 'application/json'

 data:{id:e.detail.value.id,mobile:e.detail.value.mobile,name:e.detail.value.name,address:e.detail.value.address},

Here we need to POST the data to the server.

Save method code

Public function save () {// $ user_id = 2; if (IS_POST) {$ shipping = D ('shipping'); if (! $ Shipping-> create () {$ this-> error ($ shipping-> getError (), '', true );} else {if (is_numeric ($ _ POST ['id']) {if ($ shipping-> editAddress ($ _ POST ['id']) {$ this-> success ('address modified successfully', '', true);} else {$ this-> error ('address modified failed ','', true) ;}} else {if ($ shipping-> addAddress ($ user_id) {$ this-> success ('address added successfully', '', true );} else {$ this-> error ('address addition failed', '', true );}}}}}

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

The preceding section describes how to add, delete, modify, and query instance code in a small program. For more information, see other related articles in the first PHP community!

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.