Thinkjs使用ajax实现表单提交

//前端代码
1
$('form').submit(evt=>{ 2 evt.preventDefault();//阻止表单默认提交 3 $.ajax({ 4 url: '/user/personal/update', 5 type: 'POST', 6 dataType: 'json', 7 data: $('form').serialize(), 8 success:res=>{ 9 if(!res.errno) alert('上传成功!'); 10 else alert('res.errmsg'); 11 } 12 }); 13 });
 //后台(controller)-src/user/controller/update.js
1
async indexAction(){ 2 return this.display(); 3 } 4 async updateAction(){//通过post的方式来获取值即可 5 let userList = this.model('user'); 6 let userInfo = await this.session('userInfo'); 7 let formData = this.post();//获取所有传进来的表单数据 8 let affectedRows = await userList.where({user_loginname: userInfo.login}).update({user_name: this.post('inputNickname'),user_mailbox:this.post('inputEmail'),user_tellphone:this.post('inputTell'),user_city:this.post('inputCity')}); 9 this.success();//此接口的返回值 10 }

前端通过serialize()序列化,后端通过this.post(key)获取即可,key就是html中表单元素的name值。

Serialize()的结果是一个字符串,类似表单提交的字符串。Eg:'a=1&b=cccc'。

Ajax中的type是'post',所以后端中通过this.post(key)方式获取即可。

Ps:ajax的type如果是'get',那么后端通过this.get('key')获取即可。

Ps2:在后端相当于没有用ajax,和 直接通过form的post和get提交的那种获取数据方式是相同的,但是如果要区分的话,可以通过下面这种方式来获取

具体可以参照thinkjs官方文档中的controller.get(),controller.post和controller.parma()的具体内容(https://thinkjs.org/zh-cn/doc/2.2/api_controller.html)

posted @ 2017-08-23 15:31  Kate_Lee  阅读(1752)  评论(0编辑  收藏  举报