Thinkjs使用ajax实现表单提交

时间:2022-06-19 19:50:45
//前端代码
1 $('form').submit(evt=>{
evt.preventDefault();//阻止表单默认提交
$.ajax({
url: '/user/personal/update',
type: 'POST',
dataType: 'json',
data: $('form').serialize(),
success:res=>{
if(!res.errno) alert('上传成功!');
else alert('res.errmsg');
}
});
});
 //后台(controller)-src/user/controller/update.js
1 async indexAction(){
return this.display();
}
async updateAction(){//通过post的方式来获取值即可
let userList = this.model('user');
let userInfo = await this.session('userInfo');
let formData = this.post();//获取所有传进来的表单数据
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')});
this.success();//此接口的返回值
}

前端通过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)