Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. Il programma JavaScript, alla pressione dell’uno o dell’altro pulsante, richiede al programma PHP un vettore di dati. Dopo averli ricevuti lo visualizza.
  2. Si possono vedere le richieste col metodo GET ed un parametro.
  3. <!doctype html>
  4. <head>
  5. <meta charset="UTF-8">
  6. <title>Esempio JSON - PHP</title>
  7. </head>
  8. <body>
  9. <h1 id="premi">Gli oggetti da sogno degli studenti della 5<sup>a</sup>D</h1>
  10. <button id="premi1">Vettore classico</button>
  11. <button id="premi2">Vettore associativo</button>
  12. <h2 id="mess"></h2>
  13. <ul id="elenco">
  14. <script>
  15. function acquisisciClassico() {
  16. document.getElementById("mess").innerHTML = "Vettore classico";
  17. var richiesta = new XMLHttpRequest();
  18. richiesta.onreadystatechange = function() {
  19. if(this.readyState == 4 && this.status == 200) {
  20. var elementi = JSON.parse(this.responseText);
  21. for(var i=0; i<elementi.length;i++) {
  22. var voceLista = document.createElement("li");
  23. var testoVoce = document.createTextNode(elementi[i]);
  24. voceLista.appendChild(testoVoce);
  25. document.getElementById("elenco").appendChild(voceLista);
  26. }
  27. }
  28. };
  29. richiesta.open("GET", "datiJson.php?metodo=1", true);
  30. richiesta.send();
  31. }
  32. function acquisisciAssociativo() {
  33. document.getElementById("mess").innerHTML = "Vettore associativo";
  34. var richiesta = new XMLHttpRequest();
  35. richiesta.onreadystatechange = function() {
  36. if(this.readyState == 4 && this.status == 200) {
  37. var elementi = JSON.parse(this.responseText);
  38. console.log(elementi);
  39. for(var i=0; i<elementi.length;i++) {
  40. var voceLista = document.createElement("li");
  41. var testoVoce = document.createTextNode(elementi[i].computer);
  42. voceLista.appendChild(testoVoce);
  43. document.getElementById("elenco").appendChild(voceLista);
  44. }
  45. }
  46. };
  47. richiesta.open("GET", "datiJson.php?metodo=2", true);
  48. richiesta.send();
  49. }
  50. document.getElementById("premi1").addEventListener("click", acquisisciClassico);
  51. document.getElementById("premi2").addEventListener("click", acquisisciAssociativo);
  52. </script>
  53. </ul>
  54. </body>
  55. Il programma php, letta la richesta, fornisce la prima o la seconda informazione
  56. <?php
  57. if($_GET['metodo']==1) {
  58. $sogni = array('MacBook Pro','Alfa Romeo Giulia','California','Natale');
  59. } else {
  60. $sogni = array('Star','Alfa Romeo Giulia','California','Natale');
  61. }
  62. echo json_encode($sogni);
  63. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement