我正在尝试从 js 调用 Controller 函数并将结果用于验证目的。
不幸的是,结果为 undefined
因为结果行是在 ajax 调用完成之前打印的。
这是我的代码:
*.js
send: function(e){
e.preventDefault();
var self = this;
var is_submit = self.$target.find('#is_submit').val();
var mobile = self.$target.find('#mobile').val();
var phone = self.$target.find('#phone').val();
var data = self.ajaxcall(mobile,e);
console.log('dddddddd',data);// here it prints undefined.
if (data == false){
return false;
}
this._super(e);
},
})
ajaxcall:function(mobile,e){
var value = {
'flag':'mobile',
'number':mobile
}
ajax.jsonRpc('/checkexisting/','call',value).then(function(data){
console.log('isnide ajax call',data);
return data;
});
},
这是控制台输出:
如何将其设置为同步模式?
最佳答案
没有办法让所有代码同步,可以使用callbacks
或promises/await
来等待响应。
回调示例:
{
send: function (e) {
e.preventDefault();
var self = this;
var is_submit = self.$target.find('#is_submit').val();
var mobile = self.$target.find('#mobile').val();
var phone = self.$target.find('#phone').val();
var data = self.ajaxcall(mobile, function(result){
console.log('the result is: ', result)
self._super(e);
});
},
ajaxcall: function (mobile, callback) {
var value = {
'flag': 'mobile',
'number': mobile
}
ajax.jsonRpc('/checkexisting/', 'call', value).then(function (data) {
console.log('isnide ajax call', data);
callback(data);
});
}
promise 示例:
{
send: function (e) {
e.preventDefault();
var self = this;
var is_submit = self.$target.find('#is_submit').val();
var mobile = self.$target.find('#mobile').val();
var phone = self.$target.find('#phone').val();
var data = self.ajaxcall(mobile).then(function(result){
console.log('the result is: ', result)
self._super(e);
});
},
ajaxcall: function (mobile) {
var value = {
'flag': 'mobile',
'number': mobile
}
return new Promise(function(res, rej){
ajax.jsonRpc('/checkexisting/', 'call', value).then(function (data) {
console.log('isnide ajax call', data);
res(data);
})
});
}
或者使用await(注意async
和await
关键字):
{
send: async function (e) {
e.preventDefault();
var self = this;
var is_submit = self.$target.find('#is_submit').val();
var mobile = self.$target.find('#mobile').val();
var phone = self.$target.find('#phone').val();
var data = await self.ajaxcall(mobile);
console.log(data)
self._super(e);
},
ajaxcall: function (mobile) {
var value = {
'flag': 'mobile',
'number': mobile
}
return new Promise(function(res, rej){
ajax.jsonRpc('/checkexisting/', 'call', value).then(function (data) {
console.log('isnide ajax call', data);
res(data);
})
});
}
关于javascript - 如何防止 odoo 10 中的异步执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57653402/