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

相关推荐
灰子学技术8 小时前
Envoy 底层 TCP 交互、UDS 和事件驱动技术文档
网络·网络协议·tcp/ip
wifi chicken8 小时前
wifi漫游(Roaming)802.11kvr 全协议梳理
网络·wifi·内核开发·wifi 漫游
MAXrxc9 小时前
VRRP初体验
网络
day day day ...9 小时前
MyBatis条件误写引发的查询条件污染分析与防范
java·服务器·tomcat
qq_260241239 小时前
将盾CDN:移动网络环境下的安全接入技术
网络·安全
TechMasterPlus9 小时前
Linux U-Boot 与内核启动流程深度解析:从上电到 Shell 的完整之旅
linux·运维·服务器
大白菜和MySQL9 小时前
Linux下dhcp服务搭建
linux·运维·服务器
咖喱o9 小时前
策略路由
网络
SPC的存折9 小时前
1、MySQL故障排查与运维案例
linux·运维·服务器·数据库·mysql
Deitymoon10 小时前
linux——TCP服务器获取客户端IP地址
linux·服务器·tcp/ip