Skip to content

Commit f14ae78

Browse files
committed
feat(XHR): support xhr.responseType to be "json"
1 parent b463778 commit f14ae78

File tree

1 file changed

+25
-3
lines changed

1 file changed

+25
-3
lines changed

python/pythonmonkey/builtin_modules/XMLHttpRequest.js

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -515,8 +515,8 @@ class XMLHttpRequest extends XMLHttpRequestEventTarget
515515
{
516516
if (this.#state === XMLHttpRequest.LOADING || this.#state === XMLHttpRequest.DONE)
517517
throw new DOMException('responseType can only be set before send()', 'InvalidStateError');
518-
if (!['', 'text', 'arraybuffer'].includes(t))
519-
throw new DOMException('only responseType "text" or "arraybuffer" is supported', 'NotSupportedError');
518+
if (!['', 'text', 'arraybuffer', 'json'].includes(t))
519+
throw new DOMException('only responseType "text" or "arraybuffer" or "json" is supported', 'NotSupportedError');
520520
this.#responseType = t;
521521
}
522522

@@ -550,7 +550,29 @@ class XMLHttpRequest extends XMLHttpRequestEventTarget
550550
this.#responseObject = this.#mergeReceivedBytes().buffer;
551551
return this.#responseObject;
552552
}
553+
554+
if (this.#responseType === 'json') // step 8
555+
{
556+
// step 8.2
557+
if (this.#receivedLength === 0) // response’s body is null
558+
return null;
559+
// step 8.3
560+
let jsonObject = null;
561+
try
562+
{
563+
// TODO: use proper TextDecoder API
564+
const str = decodeStr(this.#mergeReceivedBytes(), 'utf-8'); // only supports utf-8, see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value
565+
jsonObject = JSON.parse(str);
566+
}
567+
catch (exception)
568+
{
569+
return null;
570+
}
571+
// step 8.4
572+
this.#responseObject = jsonObject;
573+
}
553574

575+
// step 6 and step 7 ("blob" or "document") are not supported
554576
throw new DOMException(`unsupported responseType "${this.#responseType}"`, 'InvalidStateError');
555577
}
556578

@@ -600,7 +622,7 @@ class XMLHttpRequest extends XMLHttpRequestEventTarget
600622
#responseType = '';
601623
/**
602624
* cache for converting receivedBytes to the desired response type
603-
* @type {ArrayBuffer | string}
625+
* @type {ArrayBuffer | string | Record<any, any>}
604626
*/
605627
#responseObject = null;
606628

0 commit comments

Comments
 (0)