Home Backend Development PHP Tutorial Submission of PHP backend form in WeChat mini program

Submission of PHP backend form in WeChat mini program

Jun 08, 2018 pm 04:27 PM

This article mainly introduces the relevant information on the detailed explanation of the WeChat Mini Program PHP back-end form form submission example. Friends in need can refer to

WeChat Mini Program PHP back-end form form

1. Compared with the previous WEB PHP website building, the mini program , my personal understanding is that it just puts the web on the WeChat side, and uses the fixed format front-end of the mini program for layout and event triggering For data transmission and reading, the server can be written in any back-end language, but all data must be returned to the applet in the form of JSON.

2. Yesterday I wrote the login registration and forgotten password functions. They are essentially a form submission operation. So let’s use the registration function to write this example.

3. Directory diagram

  1. #js file is a logical control, mainly it sends requests and receives data,

  2. json is used for local configuration of this page and overrides global app.json configuration,

  3. wxss is used for page style settings,

  4. wxml is the page, which is equivalent to html

##4. I don’t care about the style and json file for now, I just want to review the submission of the form

5.Wxml file code

<view class="load-head">

  <image src="../../images/return.png" />

  注册

</view>

<view class="login">

  <form bindsubmit="formSubmit">

    <view class="field clearfix">

      <label for="name"><image src="../../images/phone.png" /></label>

      <input id="name" name="mobile" class="login-input" type="text" placeholder="请输入手机号" />

    </view>

    <view class="field clearfix">

      <label for="password"><image src="../../images/code.png" /></label>

      <input id="password" class="login-input" type="password" placeholder="请输入验证码" />

      <button class="get-code" hover-class="code-hover">获取验证码</button>

    </view>

    <view class="field clearfix">

      <label for="password"><image src="../../images/password.png" /></label>

      <input id="password" name="password" class="login-input" type="password" placeholder="请设置6-20位登录密码" />

    </view>

    <view class="field clearfix">

      <label for="repassword"><image src="../../images/password.png" /></label>

      <input id="repassword" name="repassword" class="login-input" type="password" placeholder="请输入确认密码" />

    </view>

    

    <button class="btn_login" formType="submit">注册</button>

  </form>

  <view class="reg_forget clearfix">

    <navigator url="../login/index" class="btn_reg">登录</navigator>

    <navigator url="../forget/index" class="btn_forget">忘记密码</navigator>

  </view >

  

</view>
Copy after login

## 6. Several key points need to be understood

a.Form form needs to bind a submit event. In the applet, the attribute is bindsubmit,

bindsubmit=”formSubmit

” The attribute value here is formSubmit, and the name can be Any value that conforms to the specification is equivalent to onsubmit="formSubmit()" in previous HTML. is a function name. When submitted, the formSubmit function event is triggered. 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 back-end processing is the same as before. For example, name="username" PHP can use $_POST[ 'username'] to receive.

C. Since the mini program does not have an input submit button, there must be a submit button in each form,

,

This button is used to open the submission event. 7.index.js code

Page({

 data: {

  

 },

 formSubmit: function(e) { 

  if(e.detail.value.mobile.length==0||e.detail.value.password.length==0){

   wx.showToast({

    title: &#39;手机号码或密码不得为空!&#39;,

    icon: &#39;loading&#39;,

    duration: 1500

   })

   setTimeout(function(){

     wx.hideToast()

    },2000)

  }else if(e.detail.value.mobile.length != 11){

    wx.showToast({

    title: &#39;请输入11位手机号码!&#39;,

    icon: &#39;loading&#39;,

    duration: 1500

   })

   setTimeout(function(){

     wx.hideToast()

    },2000)

  }else if(e.detail.value.password.length <6 ||e.detail.value.password.length>20){

    wx.showToast({

    title: &#39;请输入6-20密码!&#39;,

    icon: &#39;loading&#39;,

    duration: 1500

   })

   setTimeout(function(){

     wx.hideToast()

    },2000)

  }else if(e.detail.value.password != e.detail.value.repassword){

    wx.showToast({

    title: &#39;两次密码输入不一致!&#39;,

    icon: &#39;loading&#39;,

    duration: 1500

   })

   setTimeout(function(){

     wx.hideToast()

    },2000)

  }else{


   wx.request({ 

      url: &#39;https://shop.yunapply.com/home/Login/register&#39;, 

      header: { 

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

      },

      method: "POST",

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

      success: function(res) {

       if(res.data.status == 0){

         wx.showToast({

          title: res.data.info,

          icon: &#39;loading&#39;,

          duration: 1500

         })

       }else{

         wx.showToast({

          title: res.data.info,//这里打印出登录成功

          icon: &#39;success&#39;,

          duration: 1000

         })

       }

      } 

     })

  }

 }, 

})
Copy after login

##8. What needs to be noted is

Page () This method is necessary. It places a js object in it to display the effect when the page is loaded.

data: {}, data object, sets the data in the page. The front end can read this object The data inside is displayed.

formSubmit: function The methods in the mini program are all method names: function(), where function can pass in a parameter as the object that triggers the current time

The following is the execution of the function, due to verification There are too many, I only take out some of them to understand.

if(e.detail.value.mobile.length==0||e.detail.value.password.length==0){

   wx.showToast({

    title: &#39;手机号码或密码不得为空!&#39;,

    icon: &#39;loading&#39;,

    duration: 1500

   })
Copy after login

The e here is the object that currently triggers the event, similar to the html onclick="foo(this)" this object. The applet encapsulates many built-in The calling method, e.detail.value.mobile is the value of the current object name="mobile" e.detail.value.mobile.length is the length of this value

showToast is similar to alert in JS , pop-up box, title is the information displayed in the pop-up box, icon is the icon state of the pop-up box, currently there are only two states: loading and success. Duration is the time the popup box is displayed on the screen.

9. Here comes the key point

wx.request({ 

      url: &#39;https://shop.com/home/Login/register&#39;, 

      header: { 

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

      },

      method: "POST",

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

      success: function(res) {

       if(res.data.status == 0){

         wx.showToast({

          title: res.data.info,

          icon: &#39;loading&#39;,

          duration: 1500

         })

       }else{

         wx.showToast({

          title: res.data.info,//这里打印出登录成功

          icon: &#39;success&#39;,

          duration: 1000

         })

       }

      },

fail:function(){

       wx.showToast({

        title: &#39;服务器网络错误!&#39;,

        icon: &#39;loading&#39;,

        duration: 1500

       })

      }  

     })
Copy after login

wx.request({}) is a small program that initiates an https request. Note that http is not available.

Here

a.url is the URL you requested. For example, in the front end, action='index.php' in the POST form, index.php here is a relative path, and the applet The requested URL must be an absolute network path.

For example: https://shop.com/home/Login/register

b.

 header: { 

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

   },
Copy after login

Due to POST Different from the way GET transmits data, the header of POST must be

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

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

c. Be sure to specify the method: "POST". The default is "GET", keep it in capitals

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

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

d. Success callback function

success: function(res) {

  if(res.data.status == 0){

    wx.showToast({

    title: res.data.info,

    icon: &#39;loading&#39;,

    duration: 1500

    })

}else{

    wx.showToast({

    title: res.data.info,

    icon: &#39;success&#39;,

    duration: 1000

    })

   }

  }
Copy after login

e.

success:function()

is an event that is triggered successfully by the request status, also When it is 200, please note that a successful request does not mean a successful operation. The request is just a line from this program to the server.

fail:function()

is the event triggered when the network request is unsuccessful.

f.


if(res.data.status == 0){

         wx.showToast({

          title: res.data.info,

          icon: &#39;loading&#39;,

          duration: 1500

         })

       }else{

         wx.showToast({

          title: res.data.info,//这里打印出登录成功

          icon: &#39;success&#39;,

          duration: 1000

         })

       }
Copy after login

The piece of code here is related to the PHP back-end program. The specific process is Such,

1.POST通过数据到https://shop.com/home/Login/register这个接口,用过THINKPHP的就会知道是HOME模块下的Login控制下的register方法

2.register方法根据POST过来的数据,结合数据库进行二次验证,如果操作成功,返回什么,如果操作失败,返回什么

3.后端PHP代码如下:

控制器 LoginController.class.php

/**
 * 用户注册
 */
public function register()
{
  if (IS_POST) {
    $User = D("User");
    if (!$User->create($_POST, 4)) {
      $this->error($User->getError(),&#39;&#39;,true);
    } else {
      if ($User->register()){
        $this->success(&#39;注册成功!&#39;,&#39;&#39;,true);
      }else{
        $this->error(&#39;注册失败!&#39;,&#39;&#39;,true);
      }
    }
  }
}
Copy after login

模型

UserModel.class.php 的register方法

public function register()
{
  $mobile = I(&#39;post.mobile&#39;);
  $password = I(&#39;post.password&#39;);

  $res = D(&#39;User&#39;)->add(array(
    &#39;mobile&#39;=> $mobile,
    &#39;password&#39;=>md5($password),
    &#39;modifytime&#39;=>date("Y-m-d H:i:s")
  ));

  return $res;
}
Copy after login

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

相关推荐:

PHP 中TP5 Request的请求对象

php中反射的应用

PHP后端方法实现网页的分页下标生成代码

The above is the detailed content of Submission of PHP backend form in WeChat mini program. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

What is the difference between include, require, include_once, require_once? What is the difference between include, require, include_once, require_once? Apr 05, 2025 am 12:07 AM

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

See all articles