Переглянути джерело

Add AJAX button to get html fragment from server

Benoît Hubert 8 роки тому
батько
коміт
c2c91e6ced
2 змінених файлів з 18 додано та 0 видалено
  1. 16 0
      index.html
  2. 2 0
      some-text.html

+ 16 - 0
index.html

@@ -30,6 +30,9 @@
                 <button class="blue" type="submit">Say hello again</button>
             </form>
             <button class="red" id="clearForm" type="button">Clear form</button>
+
+            <div id="ajax"></div>
+            <button class="blue" id="getAjax" type="button">Get HTML with Ajax</button>
         </div>
         <script src="js/vendor/modernizr-3.5.0.min.js"></script>
         <script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
@@ -48,6 +51,7 @@
             var input = document.getElementById('inputName');
             var clearButton = document.getElementById('clearForm');
             var dateSpan = document.getElementById('todaysDate');
+            var ajaxButton = document.getElementById('getAjax');
 
             function sayHelloAgain(e) {
                 e.preventDefault();
@@ -66,8 +70,20 @@
             showDate();
             setInterval(showDate, 1000);
 
+            function loadDoc() {
+              var xhttp = new XMLHttpRequest();
+              xhttp.onreadystatechange = function() {
+                if (this.readyState == 4 && this.status == 200) {
+                 document.getElementById("ajax").innerHTML = this.responseText;
+                }
+              };
+              xhttp.open("GET", "some-text.html", true);
+              xhttp.send();
+            }
+
             form.onsubmit = sayHelloAgain;
             clearButton.onclick = clearForm;
+            ajaxButton.onclick = loadDoc;
         </script>
     </body>
 </html>

+ 2 - 0
some-text.html

@@ -0,0 +1,2 @@
+<h2>This is an example</h2>
+<p>I got this text with an AJAX request</p>