Unterschiede
Hier werden die Unterschiede zwischen zwei Versionen der Seite angezeigt.
Beide Seiten, vorherige Überarbeitung Vorherige Überarbeitung Nächste Überarbeitung | Vorherige Überarbeitung | ||
ef_informatik:voci_rest [2022-05-31 13:12] – [JavaScript] sca | ef_informatik:voci_rest [2022-05-31 13:16] (aktuell) – sca | ||
---|---|---|---|
Zeile 222: | Zeile 222: | ||
JavaScript einbinden: | JavaScript einbinden: | ||
- | <code html> | + | < |
< | < | ||
< | < | ||
Zeile 245: | Zeile 245: | ||
<script src=" | <script src=" | ||
</ | </ | ||
+ | </ | ||
+ | |||
+ | JavaScript Code: | ||
+ | <code javascript voci.js> | ||
+ | /** | ||
+ | * Function called when the user clicks the submit button or presses Enter. | ||
+ | */ | ||
+ | async function submit() { | ||
+ | // Get the original and translated words, send them to the server. | ||
+ | original = document.getElementById(" | ||
+ | translation = document.getElementById(" | ||
+ | uri = `/ | ||
+ | let response = await fetch(uri); | ||
+ | |||
+ | let response_text = await response.text(); | ||
+ | if (!response.ok) { | ||
+ | // something unexpected happened... | ||
+ | console.log(`Error: | ||
+ | return; | ||
+ | } | ||
+ | // Update the status text. | ||
+ | document.getElementById(" | ||
+ | | ||
+ | // And fetch the next word. | ||
+ | next(); | ||
+ | } | ||
+ | |||
+ | /** | ||
+ | * Update the stats. | ||
+ | */ | ||
+ | async function updateStats() { | ||
+ | uri = '/ | ||
+ | let response = await fetch(uri); | ||
+ | let response_text = await response.text(); | ||
+ | document.getElementById(" | ||
+ | } | ||
+ | |||
+ | /** | ||
+ | * Fetches a new word to translate. Called automatically after submit(), and initially for the first | ||
+ | * word. | ||
+ | */ | ||
+ | async function next() { | ||
+ | // Ensure the stats are correctly displayed. | ||
+ | updateStats(); | ||
+ | |||
+ | uri = `/random`; | ||
+ | let response = await fetch(uri); | ||
+ | let response_text = await response.text(); | ||
+ | if (!response.ok) { | ||
+ | console.log(`Error: | ||
+ | return; | ||
+ | } | ||
+ | document.getElementById(" | ||
+ | document.getElementById(" | ||
+ | } | ||
+ | |||
+ | /** Called when a key is released within input. */ | ||
+ | async function keyup(input, | ||
+ | var code = event.code; | ||
+ | if (code == " | ||
+ | submit(); | ||
+ | } | ||
+ | } | ||
+ | |||
+ | // Initial call to fetch the first word. | ||
+ | next(); | ||
</ | </ | ||