×

微信小程序使用WebService(Asp.net)进行数据交互

Kalet Kalet 发表于2019-07-26 15:01:18 浏览270 评论0

抢沙发发表评论

 

开发微信小程序掌握了数据交互的方法,再加上web的知识,基本就能开发出了,研究了下与服务器通讯,暂时不知道怎么用ajax通讯,但可以使用WebService可以进行交互尝试开发微信小程序(如果需要登录之类的,也可以自定义握手方法或使用微信登录验证:https://mp.weixin.qq.com/debug/wxadoc/dev/api/api-login.html#wxloginobject)。

1. 小程序=前端页面 + 服务器数据

2. 前端页面与服务器的交互

前端使用 wx.request请求数据(常用的有 get,和post)
服务器使用WebService处理数据,并返回结果。
使用WebService时wx.request需要使用post方式
参数对应:wx.request请求data中的参数必须与WebService中对应的参数得名称、类型一样。
3. 客户端代码
<!--index.wxml-->
<view class="container">
  <view  bindtap="bindViewTap" class="userinfo">
    <image class="userinfo-avatar" src="{{userInfo.avatarUrl}}" background-size="cover"></image>
    <text class="userinfo-nickname">{{userInfo.nickName}}</text>
  </view>
  <view class="usermotto">
    <text class="user-motto">{{motto}}</text>
   <!-- <button bindtap="onButtonchange">点击</button>
    <button bindtap="add">add</button>
    <button bindtap="remove">remove</button>-->
    <button bindtap="requestWebService">测试</button>
  </view>
</view>
requestWebService:function(){
    var that=this//注意这里必须缓存,不然无法在回调中
    获取数据后进行操作
   
    wx.request({
      url: 'http://localhost:53639/HelloServer.asmx/Name',
      data: {
        a:1,
        b:2
      },
      method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
      // header: { }, // 设置请求的 header
      success: function(res){
        // success
        console.log(res)
        that.setData({motto:res.data.d})//这里是that不是this
      },
      fail: function() {
        // fail
      },
      complete: function() {
        // complete
      }
    })
  }

4.WebService代码
   public class HelloServer : System.Web.Services.WebService
    {
 
        [WebMethod]
        public int[] Name(int a, int b)
        {
            return new int[] { a,b};
        }
    }
5.运行结果
                    
代码地址

http://download.csdn.net/detail/ywjun0919/9753671



作者:ywjun的学习笔记
原文:https://blog.csdn.net/ywjun0919/article/details/55007145

群贤毕至

访客