通过收集用户填写的表单信息提交给服务器。在窗口显示中能够看到提交的信息。
- 小程序:
- 服务器窗口:
代码结构:
- 编写app.json设置index页面-->编写index.json设置导航栏的标题文字和背景颜色-->编写index.wxml设置表单结构-->编写index.js设置表单的提交事件(wx.request()请求网络连接)-->设置本地服务器监听
- 页面结构:
编写app.json
{
"pages": [
"pages/index/index"
],
"sitemapLocation": "sitemap.json"
}
编写index.json
{
"navigationBarTitleText": "调查问卷",
"navigationBarTextStyle": "white"
}
编写index.wxml
<view>
<form bindsubmit="onSubmit">
<view>
<text>姓名:</text>
<input type="text" name="name" placeholder="请输入文字"/>
</view>
<view>
<text>性别:</text>
<radio-group name="radioGroup">
<radio checked="checked" value="nan">男</radio>
<radio value="nv">女</radio>
</radio-group>
</view>
<view>
<checkbox-group name="checkboxGroup">
<checkbox checked="checked" value="html">HTML</checkbox>
<checkbox checked="checked" value="css">CSS</checkbox>
<checkbox value="javascript">JavaScript</checkbox>
</checkbox-group>
</view>
<view>
<text>您的意见:</text>
<input type="text" name="text" />
</view>
<button form-type="submit">提交</button>
</form>
</view>
编写index.js
Page({
onSubmit:(e)=>{
wx.request({
method:'post',
url:'http://127.0.0.1:3000/',
data:e.detail.value,
success:res=>{
console.log(res);
}
})
}
})
设置本地服务器监听:
在微信开发者工具的右上角的详情中选中不校验合法域名选项,之后开始配置本地服务器。
安装Node.js服务器-->安装后按Win+R进入窗口-->node -v查看是否安装成功-->新建一个空白目录作为项目目录并在窗口中切换到该目录-->npm init -y(初始化项目并创建package.json)-->npm install express --save(安装Express框架)-->npm install nodemon -g (安装nodemon监控文件修改)-->在服务器目录下创建index.js文件并编写-->nodemon index.js(启动服务器查看是否安装成功)
服务器目录的index.js文件:
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)
})
//监听3000端口
app.listen(3000,()=>{
console.log('server running ');
})窗口显示服务器收到的信息:
小程序控制台显示服务器的响应信息: