diff --git a/HISTORY.md b/HISTORY.md index 9fb3eb9f..5febefa0 100755 --- a/HISTORY.md +++ b/HISTORY.md @@ -20,6 +20,7 @@ * updated text-to-speech library * updated bar-charts library * fixed #2850 (occasional invisible error message), thanks, Ken, for the bug report! +* extensions: added long-form xhr primitive ### 2021-06-14 * new dev version diff --git a/src/extensions.js b/src/extensions.js index 578c771a..2260b32f 100644 --- a/src/extensions.js +++ b/src/extensions.js @@ -46,7 +46,7 @@ var SnapExtensions = new Map(); example: 'lst_sort(list, fn)' - domain-prefix: 3-letter lowercase identifier followee by an underscore - e.g.: err_, lst_, txt_, dta_, map_, tts_ + e.g.: err_, lst_, txt_, dta_, map_, tts_, xhr_ - function-name: short, single word if possible, lowercase - parameter-list: comma separated names or type indicators @@ -273,3 +273,32 @@ SnapExtensions.set( return () => isDone; } ); + +// XHR: + +SnapExtensions.set( + 'xhr_request(mth, url, dta, hdrs)', + function (method, url, data, headers, proc) { + var response, i, header; + if (!proc.httpRequest) { + proc.httpRequest = new XMLHttpRequest(); + proc.httpRequest.open(method, url, true); + proc.assertType(headers, 'list'); + for (i = 1; i <= headers.length(); i += 1) { + header = headers.at(i); + proc.assertType(header, 'list'); + proc.httpRequest.setRequestHeader( + header.at(1), + header.at(2) + ); + } + proc.httpRequest.send(data || null); + } else if (proc.httpRequest.readyState === 4) { + response = proc.httpRequest.responseText; + proc.httpRequest = null; + return response; + } + proc.pushContext('doYield'); + proc.pushContext(); + } +);