首页 > web前端 > js教程 > 正文

在微信小程序中如何使用ajax实现请求服务器数据

亚连
发布: 2018-06-20 15:45:44
原创
3196 人浏览过

这篇文章主要介绍了微信小程序ajax实现请求服务器数据及模版遍历数据功能,结合实例形式分析了微信小程序ajax调用及模板wx:for循环列表渲染相关操作技巧,需要的朋友可以参考下

本文实例讲述了微信小程序ajax实现请求服务器数据及模版遍历数据功能。分享给大家供大家参考,具体如下:

昨天下载了一个微信小程序的开发者工具,大概看了一下文档,简单的用他的方法实现了ajax请求。

微信小程序文档地址:
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1474632113_xQVCl

头部标题和底部tab配置都在 app.json文件中,底部tab位最少两个,最多五个。下面是app.json文件代码和相关注释

{
 "pages":[
  "pages/index/index",
  "pages/tucao/tucao",
  "pages/center/center"
 ],
 "window":{
  "backgroundTextStyle":"",
  "navigationBarBackgroundColor": "red",
  "navigationBarTitleText": "一个标题而已",
  "navigationBarTextStyle":"white"
 },
 "tabBar": {
  "list": [{
   "pagePath": "pages/index/index",
   "text": "首页",
   "iconPath": "/images/public/menu-cd.png",
   "selectedIconPath": "/images/public/menu.png"
  },{
   "pagePath": "pages/tucao/tucao",
   "text": "吐槽",
   "iconPath": "/images/public/hot-cd.png",
   "selectedIconPath": "/images/public/hot.png"
  },{
   "pagePath": "pages/center/center",
   "text": "我的",
   "iconPath": "/images/public/center-cd.png",
   "selectedIconPath": "/images/public/center.png"
  }],
  "borderStyle": "white"
 }
}
登录后复制

这里我是通过 微信小程序wx.request实现ajax请求服务器数据的,一个程序里面最多能有五个这样的请求。下面是index.js的代码

//index.js
//获取应用实例
var app = getApp()
Page({
 data: {
  motto: 'Hello World',
  userInfo: {},
  Industry:{}
 },
 onLoad: function (res) {
  var that = this
  //调用应用实例的方法获取全局数据
  app.getUserInfo(function(userInfo){
   //更新数据
   that.setData({
    userInfo:userInfo
   })
  })
  wx.request({
   url: 'http://xx.xxxxx.com/xxx.php',//上线的话必须是https,没有appId的本地请求貌似不受影响
   data: {},
   method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
   // header: {}, // 设置请求的 header
   success: function(res){
    console.log(res.data.result)
    that.setData({
     Industry:res.data.result
    })
   },
   fail: function() {
    // fail
   },
   complete: function() {
    // complete
   }
  })
 }
})
登录后复制

其中http://xx.xxxxx.com/xxx.php的返回数据格式是一个json,格式如下

展示页面就简单了,变量{{array}} 微信模版遍历数据使用 wx:for 。index.wxml代码如下:



 
  
  {{userInfo.nickName}}
 


  {{index}}:{{item.name}}
登录后复制

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在node.js中用fs.rename如何实现强制重命名

通过javascript连接任意数据库

在laydate.js中加载路径出现错误

在vue-router中如何实现路由传参

以上是在微信小程序中如何使用ajax实现请求服务器数据的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!