如何在ServiceNow客户端脚本中不使用GlideAjax调用Script Include
在ServiceNow客户端脚本中不使用GlideAjax调用Script Include的方法
在ServiceNow里,GlideAjax是客户端与服务器端Script Include交互的标准方式,但确实存在可行的替代方案,以下是两种实用实现方式:
方案一:自定义REST API + 原生Fetch请求
这是适配性最广的替代方案,步骤清晰且适用于多数场景:
1. 搭建REST API端点
首先在ServiceNow后台创建REST API,作为客户端请求与Script Include的桥梁:
- 进入 System Web Services > REST API > REST API Definitions,新建一个API定义
- 添加资源,设置HTTP方法为
GET,自定义资源路径(比如/user-details) - 在资源脚本中直接调用Script Include逻辑:
(function process(request, response) { // 从请求参数获取用户ID var userId = request.queryParams.userId; // 实例化目标Script Include var userUtils = new global.sampleUtils(); // 调用指定方法 var userInfo = userUtils.getUserDetails(userId); // 返回处理结果给客户端 response.setBody(userInfo); response.setStatus(200); })(request, response);
2. 客户端用Fetch替代GlideAjax
替换原GlideAjax代码为原生Fetch请求,无需依赖GlideAjax:
function onChange(control, oldValue, newValue, isLoading, isTemplate) { if (isLoading || newValue === '') { return; } var userId = g_form.getValue('u_user'); // 发起Fetch请求,替换为你自己的REST API路径 fetch('/api/your-api-name/user-details?userId=' + userId, { method: 'GET', credentials: 'include' // 必须携带会话信息,否则会被权限拦截 }) .then(res => res.json()) .then(data => { // 将结果赋值到表单对应字段 g_form.setValue('u_phone', data.mobile_phone); g_form.setValue('u_email', data.email); }) .catch(err => { console.log('获取用户信息失败:', err); }); }
方案二:表单场景下用UI Action触发服务器逻辑
如果你的客户端脚本仅在表单页面运行,可以采用UI Action实现:
1. 创建服务器端UI Action
- 进入 System UI > UI Actions,新建一个UI Action
- 配置信息:
- 名称:获取用户详情
- 所属表:选择你的目标业务表
- 取消勾选「Client」(设置为服务器端执行)
- 动作名称:
get_user_details - 脚本内容:
(function executeRule(current, previous) { var userId = current.u_user.toString(); var userUtils = new global.sampleUtils(); // 调用Script Include方法并返回结果 return userUtils.getUserDetails(userId); })(current, previous);
2. 客户端调用UI Action
function onChange(control, oldValue, newValue, isLoading, isTemplate) { if (isLoading || newValue === '') { return; } // 触发UI Action并处理返回结果 g_form.submitAction('get_user_details', function(response) { var userData = JSON.parse(response); g_form.setValue('u_phone', userData.mobile_phone); g_form.setValue('u_email', userData.email); }); }
关键注意事项
- 权限控制:无论采用哪种方案,都要为REST API或UI Action配置合适的角色权限,避免未授权访问
- 会话凭证:使用Fetch时必须添加
credentials: 'include',否则ServiceNow会拒绝请求 - 禁止客户端直接使用GlideRecord:该操作会绕过服务器端安全规则,存在数据泄露风险
内容的提问来源于stack exchange,提问作者Mr world wide
相关产品推荐
相关产品推荐

