在 Frappe Framework 中,你可以通过 frappe.call 来管理 ajax 调用。frappe.call 以异步方式工作,即发送请求并通过回调机制处理响应。
frappe.call 结构
frappe.call({
method: "",
type: "POST",
args: {},
success: function(r) {},
error: function(r) {},
always: function(r) {},
btn: opts.btn,
freeze: false,
freeze_message: "",
async: true,
url: "" || frappe.request.url,
});
参数说明
method:白名单后端方法的点分路径type:字符串参数,HTTP 请求类型 “GET”、”POST”、”PUT”、”DELETE”。默认设置为 “POST”。args:关联数组,随请求传递的参数。success:函数参数,代码片段,在请求成功执行后运行error:函数参数,代码片段,在请求失败后执行always:函数参数,代码片段,无论成功或失败都会执行btn:对象参数,触发对象freeze:布尔参数,如果设置为 true,则在收到响应前冻结实例freeze_message:字符串参数,屏幕处于冻结状态时显示的消息。async:布尔参数,默认设置为 true。因此每次 frappe.call 都是异步的。若要使调用同步,请将参数值设置为 falseurl:字符串参数,发起请求的位置
如何使用 frappe.call?
调用标准 API
frappe.call({
method: 'frappe.client.get_value',
args: {
'doctype': 'Item',
'filters': {'name': item_code},
'fieldname': [
'item_name',
'web_long_description',
'description',
'image',
'thumbnail'
]
},
callback: function(r) {
if (!r.exc) {
// code snippet
}
}
});
-
参数说明:
-
doctype:你要获取信息的 DocType 名称 -
filters:条件限定符 -
fieldname:你可以在数组中指定希望在响应中返回的字段
调用白名单方法
- 在客户端,我们指定要调用的服务端
method。这是通过服务端 Python 模块的点分路径,最后一部分是方法名。
frappe.call({
method: "frappe.core.doctype.user.user.get_all_roles", //dotted path to server method
callback: function(r) {
// code snippet
}
});
- 上述请求调用服务端方法
get_all_roles,该方法位于文件$MY_BENCH/apps/frappe/frappe/core/doctype/user/user.py中:
@frappe.whitelist()
def get_all_roles():
// business logic
return value
注意:任何需要通过
frappe.call()访问的服务端方法都必须使用装饰器@frappe.whitelist()进行白名单授权。