最近写微信小程序,需要使用到动态表单,输入框都要从服务器上加载。这里分享一下解决方案。
let app = getApp()
let ajax = require('../../network/ajax')
Page({
data: {
Custom: {},
lists: []
},
onLoad: function () {
if (app.globalData.CUSTOM) //预先获取了自定义表单信息,有ID, Required两个参数
{
var array = new Array();
for(var i=0;i<app.globalData.CUSTOM.length;i++)
{
var array2 = new Array();
array2['index'] = app.globalData.CUSTOM[i]['ID']
array2['value'] = ""
array[i] = array2
}
this.setData({
Custom: app.globalData.CUSTOM,
lists: array
})
}
},
bindKeyInput: function (e) {
let id = e.currentTarget.dataset.id;
var thedata = new Array();
thedata['index'] = id
thedata['value'] = e.detail.value
this.data.lists[id] = thedata;
this.setData({
lists: this.data.lists
})
},
checkExtraInput()
{
console.log(this.data.Custom);
for(var i=0;i<this.data.lists.length;i++)
{
var value = this.data.lists[i].value;
if (this.data.Custom[i]['Required'] == 1 && value == "") return false;
}
return true;
},
bindFormSubmit: function (e){
if (!this.checkExtraInput()) {
wx.showModal({
content: '请完成表单后再试!',
showCancel: false
});
}
else
{
var array = new Object();
for(var i=0;i<this.data.lists.length;i++)
{
var array2 = new Object();
array2.id = this.data.Custom[i]['ID'];
array2.value = this.data.lists[i].value;
array[i] = array2;
}
console.log(JSON.stringify(array)); //最后转为JSON格式,Post到服务器上
});
}
}
});
发表回复