小程序网络请求

参考博客

微信小程序开发之网络请求(GET请求)
微信小程序开发之网络请求(POST请求)
微信小程序 不在以下合法域名列表中

目录

  • 介绍
  • get请求
  • post请求

介绍
一个微信小程序,同时只能有5个网络请求连接。

get请求
Api:wx.request(OBJECT)
请求参数说明
这里写图片描述

示例代码

wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
     x: '' ,
     y: ''
  },
  header: {
      'content-type': 'application/json' // 默认值
  },
  success: function(res) {
    console.log(res.data)
  }
})

success返回参数:
这里写图片描述

请求中断
返回一个 requestTask 对象,通过 requestTask,可中断请求任务。要求最低版本1.4
示例代码

const requestTask = wx.request({
  url: 'test.php', //仅为示例,并非真实的接口地址
  data: {
     x: '' ,
     y: ''
  },
  header: {
      'content-type': 'application/json'
  },
  success: function(res) {
    console.log(res.data)
  }
})

requestTask.abort() // 取消请求任务

小程序文档

post请求
与get请求差不多,需要修改的是增加一个method :”POST”方法
Tip:

  • ‘Content-Type’: ‘application/json’用在get请求中没问题. POST请求就不好使了.需要改成: “Content-Type”: “application/x-www-form-urlencoded”

示例代码:

//logs.js
const util = require('../../utils/util.js')

var app = getApp()
Page({
  data: {
    toastHidden: true,
    city_name: '',
  },
  onLoad: function () {
    that = this;
    wx.request({
      url: "https://liaolongjun.duapp.com/ace/https.do",
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: "POST",
      data: { cur: 1 },
      complete: function (json) {
        if (json == null || json.data == null) {
           console.error('网络请求失败');
           return;
         }
         wx.showModal({
           title: "提示",
           content: JSON.stringify(json.data),
           success: function (res) {
             if (res.confirm) {
               console.log("用户点击确定")
             }
           }
         });
      }
    })
  },
  onToastChanged: function () {
    that.setData({ toastHidden: true });
  }
})
var that;
//var Util = require('../../utils/util.js');

使用http请求会出现域名不合法的情况,小程序只支持https的请求

这里写图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值