|
69 | 69 | * {'id':17009,'value':'92.00','created_at':'2024-01-17 09:17:11','updated_at':null,'primary_key_identifier':'17009'}
|
70 | 70 | * {'id':17008,'value':'87.00','created_at':'2024-01-17 09:17:11','updated_at':null,'primary_key_identifier':'17008'}
|
71 | 71 | * ...
|
| 72 | + * |
| 73 | + * Example javascript code to handle this response: |
| 74 | + * |
| 75 | + * <script> |
| 76 | + * function requestStream(e,form) { |
| 77 | + * e.preventDefault(); |
| 78 | + * const outputElement = document.getElementById("streamed_operations_response"); |
| 79 | + * |
| 80 | + * outputElement.innerHTML = ''; |
| 81 | + * fetch(form.action, {method:'post', headers: { |
| 82 | + * 'Accept': 'application/json' |
| 83 | + * }, body: new URLSearchParams(new FormData(form))}) |
| 84 | + * .then(response => { |
| 85 | + * const reader = response.body.getReader(); |
| 86 | + * const decoder = new TextDecoder(); |
| 87 | + * let receivedLength = 0; |
| 88 | + * let leftOver = ''; |
| 89 | + * return new ReadableStream({ |
| 90 | + * start(controller) { |
| 91 | + * function push() { |
| 92 | + * reader.read().then(({ done, value }) => { |
| 93 | + * if (done) { |
| 94 | + * controller.close(); |
| 95 | + * return; |
| 96 | + * } |
| 97 | + * receivedLength += value.length; |
| 98 | + * const chunk = decoder.decode(value, { stream: true }); |
| 99 | + * chunk.split(/\n/).forEach(function (element) { |
| 100 | + * let row; |
| 101 | + * try { |
| 102 | + * row = JSON.parse(element); |
| 103 | + * } catch (e) { |
| 104 | + * console.log('e'); |
| 105 | + * if (leftOver === '') { |
| 106 | + * leftOver = element; |
| 107 | + * |
| 108 | + * return; |
| 109 | + * } else { |
| 110 | + * try { |
| 111 | + * row = JSON.parse(leftOver + element); |
| 112 | + * leftOver = ''; |
| 113 | + * } catch (ex) { |
| 114 | + * console.log('ex'); |
| 115 | + * leftOver += element; |
| 116 | + * console.log('This leftOver should not happen: ' + leftOver); |
| 117 | + * |
| 118 | + * return; |
| 119 | + * } |
| 120 | + * } |
| 121 | + * } |
| 122 | + * |
| 123 | + * let child = document.createElement('p'); |
| 124 | + * child.innerHTML = JSON.stringify(row) |
| 125 | + * outputElement.appendChild(child); |
| 126 | + * }); |
| 127 | + * controller.enqueue(value); |
| 128 | + * push(); |
| 129 | + * }); |
| 130 | + * } |
| 131 | + * push(); |
| 132 | + * } |
| 133 | + * }); |
| 134 | + * }) |
| 135 | + * .then(stream => new Response(stream)) |
| 136 | + * .then(response => response.text()) |
| 137 | + * .then(data => { |
| 138 | + * console.log("Streaming complete"); |
| 139 | + * }) |
| 140 | + * .catch(error => { |
| 141 | + * console.error("Streaming error:", error); |
| 142 | + * }); |
| 143 | + * } |
| 144 | + * </script> |
72 | 145 | */
|
73 | 146 | class StreamedJsonResponse extends StreamedResponse
|
74 | 147 | {
|
|
0 commit comments