搜索
首页后端开发php教程在微信小程序中PHP后端form表单的提交

这篇文章主要介绍了微信小程序 PHP后端form表单提交实例详解的相关资料,需要的朋友可以参考下

微信小程序 PHP后端form表单

1.小程序相对于之前的WEB+PHP建站来说,个人理解为只是将web放到了微信端,用小程序固定的格式前前端进行布局、事件触发和数据的输送和读取,服务器端可以用任何后端语言写,但是所有的数据都要以JSON的形式返回给小程序。

2.昨天写了登录注册、忘记密码功能,他们实质上都是一个表单提交操作。因此就拿注册功能来写这个例子。

3.目录图

  1. js文件是逻辑控制,主要是它发送请求和接收数据,

  2. json 用于此页面局部 配置并且覆盖全局app.json配置,

  3. wxss用于页面的样式设置,

  4. wxml就是页面,相当于html

4.样式和json文件暂时不管了,我只是想回顾一下form表单的提交

5.Wxml文件代码

<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>

 6.其中几个关键点需要理解

a.Form表单,需要绑定一个submit事件,在小程序中,属性为bindsubmit,

bindsubmit=”formSubmit”   这里的属性值formSubmit,命名可以为符合规范的任意值,相当于以前html中的  onsubmit=”formSubmit()”,是一个函数名,当提交的时候触发formSubmit这个函数事件,这个函数写在js中。

b.其他的属性和之前的HTML差不多,注意的是,表单一定要有name=“value”,后端处理和以前一样,比如name=”username” PHP可以用 $_POST[‘username']来接收。

C.由于小程序没有input submit这个按钮,所以在每个form表单中都要有一个提交按钮,

cbc47cc7c46af5112c7354a7ad9ae6ad注册65281c5ac262bf6d81768915a4a77ac0,这个按钮就是用来开启提交事件的。

7.index.js代码

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

         })

       }

      } 

     })

  }

 }, 

})

8.需要注意的是

Page()这个方法是必须有的,里面放置js对象,用于页面加载的时候,呈现效果

data: {},数据对象,设置页面中的数据,前端可以通过读取这个对象里面的数据来显示出来。

formSubmit: function  小程序中方法都是 方法名:function(),其中function可以传入一个参数,作为触发当前时间的对象

下面是函数的执行,由于验证太多,我只拿一部分出来理解。

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

   wx.showToast({

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

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

    duration: 1500

   })

 这里的e,就是当前触发事件的对象,类似于html onclick=“foo(this)”this对象,小程序封装了许多内置的调用方法,e.detail.value.mobile 就是当前对象name=”mobile”的对象的值e.detail.value.mobile.length就是这个值的长度

 showToast类似于JS中的alert,弹出框,title  是弹出框的显示的信息,icon是弹出框的图标状态,目前只有loading 和success这两个状态。duration是弹出框在屏幕上显示的时间。 

9.重点来了

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

       })

      }  

     })

 wx.request({})是小程序发起https请求,注意http是不行的。

 这里

a.url是你请求的网址,比如以前在前端,POST表单中action=‘index.php',这里的index.php是相对路径,而小程序请求的网址必须是网络绝对路径。

比如:https://shop.com/home/Login/register

b.

 header: { 

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

   },

由于POST和GET传送数据的方式不一样,POST的header必须是

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

GET的header可以是 'Accept': 'application/json'

c.一定要写明method:“POST”  默认是“GET”,保持大写

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

这里的data就是POST给服务器端的数据 以{name:value}的形式传送

d.成功回调函数

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

    })

   }

  }

e.success:function()是请求状态成功触发是事件,也就是200的时候,注意,请求成功不是操作成功,请求只是这个程序到服务器端这条线的通的。

fail:function()就是网络请求不成功,触发的事件。

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

         })

       }

这里的一段代码是和PHP后端程序有关系的,具体流程是这样的,

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);
      }
    }
  }
}

 模型

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;
}

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

相关推荐:

PHP 中TP5 Request的请求对象

php中反射的应用

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

以上是在微信小程序中PHP后端form表单的提交的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
使用PHP发送电子邮件的最佳方法是什么?使用PHP发送电子邮件的最佳方法是什么?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

PHP中依赖注入的最佳实践PHP中依赖注入的最佳实践May 08, 2025 am 12:21 AM

使用依赖注入(DI)的原因是它促进了代码的松耦合、可测试性和可维护性。1)使用构造函数注入依赖,2)避免使用服务定位器,3)利用依赖注入容器管理依赖,4)通过注入依赖提高测试性,5)避免过度注入依赖,6)考虑DI对性能的影响。

PHP性能调整技巧和技巧PHP性能调整技巧和技巧May 08, 2025 am 12:20 AM

phperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovesponsemetimes.2)优化

PHP电子邮件安全性:发送电子邮件的最佳实践PHP电子邮件安全性:发送电子邮件的最佳实践May 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

您如何优化PHP应用程序的性能?您如何优化PHP应用程序的性能?May 08, 2025 am 12:08 AM

TOOPTIMIZEPHPAPPLICITIONSFORPERSTORANCE,USECACHING,数据库imization,opcodecaching和SererverConfiguration.1)InlumentCachingWithApcutCutoredSatfetchTimes.2)优化的atabasesbasesebasesebasesbasesbasesbaysbysbyIndexing,BeallancingAndWriteExing

PHP中的依赖注入是什么?PHP中的依赖注入是什么?May 07, 2025 pm 03:09 PM

依赖性注射inphpisadesignpatternthatenhancesFlexibility,可检验性和ManiaginabilybyByByByByByExternalDependencEctenceScoupling.itallowsforloosecoupling,EasiererTestingThroughMocking,andModularDesign,andModularDesign,butquirscarecarefulscarefullsstructoringDovairing voavoidOverOver-Inje

最佳PHP性能优化技术最佳PHP性能优化技术May 07, 2025 pm 03:05 PM

PHP性能优化可以通过以下步骤实现:1)在脚本顶部使用require_once或include_once减少文件加载次数;2)使用预处理语句和批处理减少数据库查询次数;3)配置OPcache进行opcode缓存;4)启用并配置PHP-FPM优化进程管理;5)使用CDN分发静态资源;6)使用Xdebug或Blackfire进行代码性能分析;7)选择高效的数据结构如数组;8)编写模块化代码以优化执行。

PHP性能优化:使用OpCode缓存PHP性能优化:使用OpCode缓存May 07, 2025 pm 02:49 PM

opcodecachingsimplovesphperforvesphpermance bycachingCompiledCode,reducingServerLoadAndResponSetimes.1)itstorescompiledphpcodeinmemory,bypassingparsingparsingparsingandcompiling.2)useopcachebachebachebachebachebachebachebysettingparametersinphametersinphp.ini,likeememeryconmorysmorysmeryplement.33)

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。