微信小程序页面交互综合练习 (重点:解决“setData of undefined”报错问题)

一、写一个注册表单,点击"注册"按钮将用户输入的数据带到服务器,并且能在控制台显示参数。

(1)首先,我需要在vscode里面创建一个简易的node.js服务器

javascript 复制代码
//第一步:引入http模块
var http =require('http');
//第二步:创建服务器
http.createServer(function(request,response){
//发送http头部
response.writeHead(200,{'Content-Type':'text/plain'});
//获取请求参数
console.log(request.url);
//发送响应数据
response.end(`[
        { "name": "JavaScript高级程序设计", "author": "扎卡斯", "price": "¥78.20" },
        { "name": "HTML5移动Web开发", "author": "黑马程序员", "price": "¥39.50" },
        { "name": "MongoDB设计模式", "author": "科普兰", "price": "¥28.40" }
    ]`);
}).listen(8888);//使用 listen 方法绑定 8888 端口
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

(2)然后,需要在微信小程序开发工具的index.wxml里写一个注册表单

html 复制代码
<navigation-bar title="注册" back="{{false}}" color="black" background="#FFF"></navigation-bar>
<scroll-view class="scrollarea" scroll-y type="list">
<view>用户名:</view>
<input type="text" model:value="{{username}}"/>
<view>密码:</view>
<input type="text" model:value="{{password}}"/>
<view>性别:</view>
<radio-group style="display: flex;" bind:change="test1">
      <radio value="man"/>男
      <radio value="woman"/>女
</radio-group>
<view>爱好:</view>
<checkbox-group style="display: flex;" bind:change="test2">
  <checkbox value="sing"/>唱歌
  <checkbox value="dance"/>跳舞
  <checkbox value="ball"/>打篮球
  </checkbox-group>
  <view>
    <button bind:tap="regist">注册</button>
  </view>
</scroll-view>

页面如下:

(3)最后在index.js里面给绑定的函数写上执行代码:

javascript 复制代码
Page({
    data: { //初始数据
        username:"",
        password:""
    },
   test1:function(e){ //性别
       this.setData({
           sex:e.detail.value
       })
   },
   test2:function(e){ //爱好
    console.log((e.detail.value).join(","));
    this.setData({
        hobby:e.detail.value
    })
   },
   regist:function(){ //点击注册
       wx.request({
         url: 'http://127.0.0.1:8888',
         method:"GET",
         data:this.data
       })
   }
})

(4)代码运行结果:

我在vscode中运行创建服务器代码

当我填好表单数据点击提交

vscode终端如图显示:

二、将服务器里的数据渲染在我的wxml页面。注意数据显示前需要有"加载中"提示和"加载完毕"提示

(1)和题一 一样先运行我的vscode创建服务器代码,运行此代码

javascript 复制代码
//第一步:引入http模块
var http =require('http');
//第二步:创建服务器
http.createServer(function(request,response){
//发送http头部
response.writeHead(200,{'Content-Type':'text/plain'});
//获取请求参数
console.log(request.url);
//发送响应数据
response.end(`[
        { "name": "JavaScript高级程序设计", "author": "扎卡斯", "price": "¥78.20" },
        { "name": "HTML5移动Web开发", "author": "黑马程序员", "price": "¥39.50" },
        { "name": "MongoDB设计模式", "author": "科普兰", "price": "¥28.40" }
    ]`);
}).listen(8888);//使用 listen 方法绑定 8888 端口
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');

(2)在微信小程序开发工具index.wxml搭建好静态页面

html 复制代码
<navigation-bar title="书店商城" back="{{false}}" color="black" background="#FFF"></navigation-bar>
<scroll-view class="scrollarea" scroll-y type="list">
<view wx:for="{{result}}" class="styles">
{{item.name}}
{{item.author}}
{{item.price}}
</view>
</scroll-view>

(3)最后在index.js里面给绑定的函数写上执行代码:

如果在普通函数里依旧使用this.setData一定会出现"setData of undefined"的报错,我们可以通过两种方法来解决:

1.使用箭头函数 =>,箭头函数的this就是指向当前页面了
2.使用var that=this普通函数。定义一个变量that将当前页面对象保存下来,把所有的this改为that,就可以使用当前页面对象来操作
3.特别注意二者区别:在箭头函数中,this 的值是在函数定义时确定的,而不是在调用时确定的。而在普通函数中,this 的值是在函数被调用时确定的,所以得写在onLoad里面。

javascript 复制代码
Page({
    data: {
        result: [],
    },
    onLoad: function () {//onLoad生命周期函数。监听页面加载,且一个页面只会在创建完成后触发一次。就相当于出生
        var that = this;
        wx.showLoading({
            title: '正在加载...',
        });
        wx.request({
            url: 'http://127.0.0.1:8888/',
            method: "GET",
            //   注意:解决setData is undefined报错问题,我们可以使用两种方法来解决。
            // 1.使用箭头函数 =>,箭头函数的this就是指向当前页面了
            //  2.使用var that=this普通函数。定义一个变量that将当前页面对象保存下来,把所有的this改为that,就可以使用当前页面对象来操作
            // *二者区别注意:在箭头函数中,this 的值是在函数定义时确定的,而不是在调用时确定的。而在普通函数中,this 的值是在函数被调用时确定的,所以得写在onLoad里面。
            // 一、箭头函数实现:
            //   success:res=>{
            //     wx.hideLoading();
            //     wx.showToast({
            //       title: '加载完毕',
            //       icon: "success",
            //       duration:2000
            //     });
            //     this.setData({
            //         result:res.data,
            //     })
            //   }

            // 二、var that=this普通函数实现
            success: function (res) {
                wx.hideLoading();
                wx.showToast({
                    title: '加载完毕',
                    icon: "success",
                    duration: 2000
                });
                that.setData({
                    result: res.data
                })
            }



        })
    }
})

(4)页面结果显示:

相关推荐
万象.1 小时前
Linux数据链路层通信原理及报文格式
linux·网络·网络协议
卷Java2 小时前
Linux服务器Docker部署OpenClaw:腾讯云/阿里云/VPS安装避坑指南
linux·运维·服务器
原来是猿3 小时前
Linux-【动静态库】
linux·运维·服务器
深圳市恒讯科技4 小时前
云服务器怎么选?从CPU、内存到IOPS的零基础选型手册
运维·服务器
victory04314 小时前
Agent 面试知识树 + 高频追问答案库
网络·面试·职场和发展
艾莉丝努力练剑5 小时前
【脉脉】AI创作者崛起:掌握核心工具,在AMA互动中共同成长
运维·服务器·c++·人工智能·安全·企业·脉脉
Blurpath住宅代理6 小时前
原生IP vs 广播IP:如何从网络层判断代理IP的“真实性”?
网络·静态ip·动态ip·代理·代理ip·住宅ip·住宅代理
chinesegf6 小时前
DNS 验证验证SSL证书
linux·服务器·网络
猿饵块7 小时前
python--websocket
网络·websocket·网络协议
taxunjishu7 小时前
塔讯总线协议转换信捷 PLC 对接 TCP/IP 设备实战方案
网络·物联网·自动化