微信小程序 用get/post提交form数据 调用接口并循环显示在页面

版权声明:本文为博主原创文章,未经博主允许不得镜像、转载。 https://blog.csdn.net/qq_21041889/article/details/89643195

在开发微信小程序的过程中,有调用接口的情况,(如果是想找免费接口用来测试或者玩的,可以去免费开放接口API找免费的API接口)


本篇文章以表单提交 调用天气预报的接口 https://apis.juhe.cn/simpleWeather/query

下面是wxml代码,一个简单的表单提交页面

<view wx:if="{{item == ''}}">
  <form bindsubmit="formSubmit" bindreset="formReset">
    <view class="cu-form-group margin-top">
      <view class='title'>输入要查询的城市名称</view>
      <input class='radius' id='city' name="city"></input>
    </view>
    <view class="padding flex flex-direction">
    <button class='cu-btn bg-red margin-tb-sm lg'formType="submit">提交</button>
    </view>
  </form>
</view>

效果图 

下面是js文件

//定义页面的result_list为空,这里给一个空的数组,下面初始化加载的时候,会去给这个arc_list赋值
  data: {
    result_list:[],
    item :[],
  },
  formSubmit:function(e){
    var obj = this;
    var post = e.detail.value;
    // console.log(e.detail.value);
    //请求接口
  wx.request({
    //这里是你要调用的接口
    url: 'https://apis.juhe.cn/simpleWeather/query',
    header: {
      "Content-Type": "application/x-www-form-urlencoded"
    },
    method: "POST",
    data: { 
       //这里是你请求需要发送的参数
      city: post.city,
      key: '***************',//key值需要申请
      },
    success: function (res) {
       //请求成功后的回调
      console.log(res.data.result);
      // var result = res.data.result,
      //赋值
      obj.setData({
        item: res.data.result ,
        // realtime: res.data.result.city.realtime
      })
    },
    fail: function () {
      console.log('提交失败');
    }
  })
},

 下面是调用成功后返回的数据

最后 我们在页面进行简单循环一下 

<view wx:if="{{item != ''}}">
  {{item.city}}
  当日天气:{{item.realtime.info}},此时气温{{item.realtime.temperature}}
  未来5天天气:
  <view wx:for="{{item.future}}" wx:key="navItems2" wx:for-index="index" wx:for-item="f">
  {{f.date}}{{f.weather}}{{f.temperature}}{{f.direct}}
  </view>
</view>

简简单单循环一下,就得到下面效果的页面 

以上就是直接以表单提交调用天气预报的接口 ,如何直接请求接口并循环显示在页面,上一篇文章见或者直接点击链接访问~  

猜你喜欢

转载自blog.csdn.net/qq_21041889/article/details/89643195
今日推荐