Last active
April 23, 2024 11:28
-
-
Save codaroma/1f2c05f91913a3a625937c73f28af7fc to your computer and use it in GitHub Desktop.
ServiceNow SimpleQueryAjax.js Script Include
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Example usage | |
* | |
* function onChange(control, oldValue, newValue, isLoading) { | |
* if (isLoading || newValue == "") { | |
* return; | |
* } | |
* | |
* var ajax = new GlideAjax("SimpleQueryAjax"); | |
* ajax.addParam( | |
* "sysparm_value", | |
* JSON.stringify({ | |
* table: "sys_user", | |
* query: "sys_id=" + newValue, | |
* limit: 1, | |
* fields: ["manager", "manager$DISPLAY"], | |
* }) | |
* ); | |
* | |
* ajax.getXMLAnswer(function (answer) { | |
* var result = JSON.parse(answer); | |
* if (result.output.records.length) { | |
* g_form.setValue( | |
* "vManager", | |
* result.output.records[0].manager, | |
* result.output.records[0].manager$DISPLAY | |
* ); | |
* } | |
* }); | |
* } | |
*/ | |
var SimpleQueryAjax = Class.create(); | |
SimpleQueryAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, { | |
process: function() { | |
var MAX_RECORDS = 1000; | |
var resp = { | |
input: JSON.parse(this.getValue()), | |
output: { | |
records: [], | |
run_as: { | |
user_name: gs.getUserName(), | |
user_id: gs.getUserID() | |
}, | |
error: null | |
} | |
}; | |
if (typeof resp.input.query !== 'string') { | |
resp.input.query = ''; | |
} | |
if (typeof resp.input.limit !== 'number' || resp.input.limit < 1 || resp.input.limit > MAX_RECORDS) { | |
resp.input.limit = MAX_RECORDS; | |
} | |
if (!Array.isArray(resp.input.fields)) { | |
if (typeof resp.input.fields === 'string') | |
resp.input.fields = [resp.input.fields]; | |
else | |
resp.input.fields = []; | |
} | |
try { | |
if (!resp.input.table) throw new Error('Invalid table property'); | |
GlideQuery.parse(resp.input.table, resp.input.query) | |
.withAcls() | |
.limit(resp.input.limit) | |
.select(resp.input.fields) | |
.forEach(function(record) { | |
resp.output.records.push(record); | |
}); | |
} catch (error) { | |
resp.output.error = error; | |
} | |
return JSON.stringify(resp); | |
}, | |
type: 'SimpleQueryAjax' | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment