This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| programmieren:javascript:alpinejs_ajax_beispiel [2022/09/14 08:01] – created jgehrke | programmieren:javascript:alpinejs_ajax_beispiel [2022/12/17 12:28] (current) – external edit 127.0.0.1 | ||
|---|---|---|---|
| Line 7: | Line 7: | ||
| Mini Beispiel zur Verdeutlichung: | Mini Beispiel zur Verdeutlichung: | ||
| - | < | + | < |
| // dummy data | // dummy data | ||
| function alpinejs_dummy_ajax_app(){ | function alpinejs_dummy_ajax_app(){ | ||
| Line 28: | Line 28: | ||
| Im Beispiel mit dem Ajax call sieht es dann so aus: | Im Beispiel mit dem Ajax call sieht es dann so aus: | ||
| - | < | + | < |
| function alpinejs_dummy_ajax_app(){ | function alpinejs_dummy_ajax_app(){ | ||
| Line 40: | Line 40: | ||
| ' | ' | ||
| - | ' | + | ' |
| - | // AJAX POST VORBEREITEN | + | // PREPARE |
| - | const ajax_post_url = | + | const ajax_post_url = |
| const xhttp = new XMLHttpRequest(); | const xhttp = new XMLHttpRequest(); | ||
| xhttp.open( ' | xhttp.open( ' | ||
| xhttp.setRequestHeader(" | xhttp.setRequestHeader(" | ||
| xhttp.onreadystatechange = function() { | xhttp.onreadystatechange = function() { | ||
| - | if(this.readyState == 4 && this.status == 200) { | + | const is_call_success = (this.readyState == 4 && this.status == 200) ? true : false; |
| + | |||
| + | if( is_call_success | ||
| const response_json = JSON.parse( this.response ); | const response_json = JSON.parse( this.response ); | ||
| - | console.log( " | + | /* |
| - | console.log( response_json ); | + | |
| - | + | we need to write the response data to the alpine.js object. | |
| - | // Zurück auf dieses Modul die Daten schreiben | + | So we be bound the current alpine.js object to a global window variable |
| - | // Dafür unten die Zeile mit (*) beachten! | + | */ |
| - | window.this_alpinejs_module.repsonse_json = response_json; | + | window.this_alpinejs_module.repsonse_json = response_json; |
| return true; | return true; | ||
| Line 61: | Line 63: | ||
| }; | }; | ||
| - | // AJAX DURCHFÜHREN | + | // DO THE AJAX POST |
| const data = JSON.stringify( this.dummy_data() ); | const data = JSON.stringify( this.dummy_data() ); | ||
| xhttp.send( data ); | xhttp.send( data ); | ||
| Line 67: | Line 69: | ||
| init() { | init() { | ||
| - | console.log( " | + | /* |
| - | console.log( this.dummy_data() ); | + | This makes the alpine.js object available out of 'this' current context. |
| - | + | e.g. for methods in other objects | |
| - | // POST CALL DIREKT STARTEN | + | */ |
| - | this.submit_data(); | + | |
| - | + | ||
| - | // (*) DAS IST WICHTIG, DASS WIR DATEN AUS DEM AJAX RESPONSE ZURÜCK | + | |
| - | // INS ALPINE SCHREIBEN KÖNNEN | + | |
| window.this_alpinejs_module = this; // <-- I M P O R T A N T | window.this_alpinejs_module = this; // <-- I M P O R T A N T | ||
| } | } | ||