在微信小程序中也存在form組件,bindsubmit這個屬性可以用于攜帶 form 中的數(shù)據(jù)觸發(fā) submit 事件,它鞋帶的參數(shù)形式如下:
1 | event.detail =
{value : {'name':
'value'} , formId:
''} |
其中的name,和一般的網(wǎng)頁一樣,將需要上傳的input等表單組件設置name屬性,在這里,form傳遞的參數(shù),使用name作為一個key
提交動作是由<form/> 表單中 formType 為 submit 的 <button/> 組件來控制的,示例如下:
1 | <button form-type="submit" class='search'><span>開始計算</span></button> |
當點擊這個button時,會觸發(fā)bindsubmit綁定的js文件中的事件,例如:
1 2 3 4 | <form bindsubmit="formSubmit" bindreset="formReset"> <input type="text" name="price"/><button form-type="submit" class='search'><span>開始計算</span></button></form> |
在這里,點擊這個button則會調(diào)用js中的formSubmit,同時在formSubmit事件中可以用e.detail.value.price的方式獲取name為price的組件的value值,js中formSubmit的定義如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | formSubmit:
function (e)
{ this.setData({ price: e.detail.value.price, //用e.detail.value.price,獲取了form中name為price組件的value,賦值給js文件data中定義的price變量 }) var that = this; //在success部分,this失效,需要先將this賦值給that,通過調(diào)用that代替this比如:that.setData({}) wx.request({ //使用微信提供的wx.request完成信息交互 url: config.service.XXXX, //url的值統(tǒng)一定義在了configuration.js中,在本js開始時var config =
require('../../config');引入 header: { "Content-Type": "application/x-www-form-urlencoded" //使用form方式傳遞參數(shù) }, method: "POST", dataType:"json", data: Util.json2Form({ price: this.data.price }),
//將要傳遞的數(shù)據(jù)使用util.js中的json2Form轉(zhuǎn)為標注的form數(shù)據(jù)格式 success: function (res) { //res是返回的數(shù)據(jù),success是響應成功后執(zhí)行部分 console.log(res.data) //顯示res中攜帶的數(shù)據(jù) }, complete: function (res) { //
complete類似finally,最后必然執(zhí)行 if (res == null || res.data ==
null) {
//如果返回值為空,則提示網(wǎng)絡請求失敗 console.error('網(wǎng)絡請求失敗'); return; } } }) }, |
util.js的內(nèi)容:
1 2 3 4 5 6 7 8 9 10 | function json2Form(json) { var str = []; for (var p in json) { str.push(encodeURIComponent(p) + "=" +
encodeURIComponent(json[p])); } return str.join("&");}module.exports =
{ json2Form: json2Form,} |
wx.request也可以使用功能json格式傳輸數(shù)據(jù),但是個人后臺不太習慣處理json文件
