微信小程序页面交互综合练习 (重点:解决“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)页面结果显示:

相关推荐
给生活加糖!24 分钟前
智能交通系统(Intelligent Transportation Systems):智慧城市中的交通革新
网络·人工智能·智慧城市
菜菜小蒙35 分钟前
【Linux】基于UDP/TCP服务器与客户端的实现
linux·服务器·udp
人间打气筒(Ada)36 分钟前
ubuntu网络及软件包管理
网络·ubuntu·php
web2u1 小时前
Docker入门及基本概念
java·运维·服务器·spring·docker·容器
明达技术1 小时前
工控自动化领域:数字量信号与模拟量信号的差异解析
网络
网安Ruler2 小时前
靶场之路-Kioptix Level-1 mod_ssl 缓冲区溢出漏洞
网络·网络协议·网络安全·ssl
alden_ygq2 小时前
Ollama 模型交互
microsoft·交互
qq_301787452 小时前
FunAudioLLM:用语音大模型解锁智能语音交互的无限可能
交互
深耕云原生2 小时前
浅谈网络 | 容器网络之Cilium
网络·ebpf·cilium
漫谈网络2 小时前
Ryu:轻量开源,开启 SDN 新程
网络·开源·信息与通信