最近在做H5相關功能頁面用於手機app的使用,此功能類似於登記,有許多表單項填寫,在H5中有button選擇項不便使用form表單提交數據到后台接收,所以只能單獨根據元素ID獲取值。
因為涉及到數十項相關表單項因此考慮有更簡便的獲取表單值方法,即遍歷頁面所有input元素、button元素進行值的獲取代碼如下:
for(var ele of $.find('input')){
alert(ele.value);
}
通過$.find('input') 獲取到頁面所有輸入項元素數組,進一步想到通過muiajax向后提交數據正好用獲取到的輸入項元素數組賦值給data:{}
var Formdata = {};
for(var ele of $.find('.mui-btn.mui-btn-block')){
Formdata[ele.name] = ele.innerText
}
mui.ajax('/abc/def/submit.action',{
data:Formdata ,
dataType:'json',//服務器返回json格式數據
type:'post',//HTTP請求類型
timeout:10000,//超時時間設置為10秒;
success:function(data){
mui.alert('success!');
},
error:function(xhr,type,errorThrown){
//異常處理;
mui.alert(xhr.response==""?type:mui.parseJSON(xhr.response).msg);
console.log(xhr.response==""?type:mui.parseJSON(xhr.response).msg);
}
});
}, false);
