案例链接
页面效果
页面设计
<view class="container"> <form bindsubmit="submit"> <view> <text>姓名:</text> <input name="name" value="{{name}}" /> </view> <view> <text>性别:</text> <radio-group name="gender"> <label wx:for="{{gender}}" wx:key="value"> <radio value="{{item.value}}" checked="{{item.checked}}" /> {{item.name}} </label> </radio-group> </view> <view> <text>专业技能:</text> <checkbox-group name="skills"> <label wx:for="{{skills}}" wx:key="value"> <checkbox value="{{item.value}}" checked="{{item.checked}}" /> {{item.name}} </label> </checkbox-group> </view> <view> <text>您的意见:</text> <textarea name="opinion" value="{{opinion}}" /> </view> <button form-type="submit">提交</button> </form> </view>
页面样式
.container { margin: 50rpx; } view { margin-bottom: 30rpx; } input { width: 600rpx; margin-top: 10rpx; border-bottom: 2rpx solid #ccc; } label { display: block; margin: 8rpx; } textarea { width: 600rpx; height: 100rpx; margin-top: 10rpx; border: 2rpx solid #eee; }
页面逻辑
前端发送请求到后端,后端传回 json 数组赋值给 data
// pages/index/index.js Page({ /** * 页面的初始数据 */ data: { }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { wx.request({ url: 'http://127.0.0.1:3000/', success: res => { console.log(res.data) this.setData(res.data) } }) }, submit: function(e) { wx.request({ method: 'post', url: 'http://127.0.0.1:3000/', data: e.detail.value, success: function(res) { console.log(res) } }) } })
后端代码(node.js)
直接 node index.js 启动即可 (node.js不会的小伙伴可以参考我的node.js专栏 https://blog.csdn.net/weixin_45525272/category_10080631.html?spm=1001.2014.3001.5482)
const express = require('express') const bodyParser = require('body-parser') const app = express() app.use(bodyParser.json()) // 处理POST请求 app.post('/', (req, res) => { console.log(req.body) res.json(req.body) }) var data = { name: '张三', gender: [ { name: '男', value: '0', checked: true }, { name: '女', value: '1', checked: false } ], skills: [ { name: 'HTML', value: 'html', checked: true }, { name: 'CSS', value: 'css', checked: true }, { name: 'JavaScript', value: 'js', checked: true }, { name: 'Photoshop', value: 'ps', checked: false }, ], opinion: '测试' } // 处理GET请求 app.get('/', (req, res) => { res.json(data) }) // 监听3000端口 app.listen(3000, () => { console.log('server running at http://127.0.0.1:3000') })