微信小程序 PHP后端form表单提交实例详解(2)

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

9.重点来了

wx.request({ url: 'https://shop.com/home/Login/register', 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: 'loading', duration: 1500 }) }else{ wx.showToast({ title: res.data.info,//这里打印出登录成功 icon: 'success', duration: 1000 }) } }, fail:function(){ wx.showToast({ title: '服务器网络错误!', icon: 'loading', 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: 'loading', duration: 1500 }) }else{ wx.showToast({ title: res.data.info, icon: 'success', duration: 1000 }) } }

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

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

f.

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

这里的一段代码是和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(),'',true); } else { if ($User->register()){ $this->success('注册成功!','',true); }else{ $this->error('注册失败!','',true); } } } }

模型

UserModel.class.php  的register方法

public function register() { $mobile = I('post.mobile'); $password = I('post.password'); $res = D('User')->add(array( 'mobile'=> $mobile, 'password'=>md5($password), 'modifytime'=>date("Y-m-d H:i:s") )); return $res; }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwdxzx.html