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

相关推荐
wanhengidc1 分钟前
云手机的硬件依赖性如何?
运维·服务器·智能手机·云计算
VekiSon12 分钟前
Linux系统编程——标准IO
linux·运维·服务器
kaikaile199519 分钟前
LDPC编解码与未编码信息的误码率比较
网络
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ37 分钟前
aspect实现请求校验,但是WebSocket 端点类不能被 AOP 代理解决方案
网络·websocket·网络协议
Evan芙1 小时前
DNS服务器类型,解析答案,正反解析域,资源记录定义总结
运维·服务器
wanhengidc1 小时前
巨椰 云手机办公便利性高
运维·服务器·安全·智能手机·云计算
数字护盾(和中)1 小时前
从边界突破到物理破坏:APT 工控攻击链路与防御闭环
网络
Saniffer_SH1 小时前
【每日一题】PCIe答疑 - 接大量 GPU 时主板不认设备或无法启动和MMIO的可能关系?
运维·服务器·网络·人工智能·驱动开发·fpga开发·硬件工程
大白的编程日记.1 小时前
【计算网络学习笔记】Socket编程UDP实现简单聊天室
网络·笔记·学习
织元Zmetaboard1 小时前
什么是态势感知大屏?
网络·数据库