ajax.jsp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: 武恒
  4. Date: 2023/2/10
  5. Time: 11:27
  6. To change this template use File | Settings | File Templates.
  7. --%>
  8. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9. <html>
  10. <head>
  11. <title>Ajax</title>
  12. </head>
  13. <body>
  14. <div style="width: 800px; margin: 0 auto">
  15. <button onclick="sendData()" > sendData </button>
  16. <button onclick="document.getElementById('ajax-respone').innerHTML = '' " > cleanData </button>
  17. <div id="ajax-respone" style="width: 800px; height: 390px; border: 1px solid red; overflow: auto;">
  18. </div>
  19. </div>
  20. <script>
  21. var sendData = function(){
  22. var xmlHttpRequest = new XMLHttpRequest();
  23. xmlHttpRequest.onreadystatechange = function () {
  24. if ( xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200 ) {
  25. //document.getElementById("ajax-respone").innerHTML = xmlHttpRequest.responseText;
  26. var parse = JSON.parse( xmlHttpRequest.responseText );
  27. for (let i = 0; i < parse.length; i++) {
  28. let str = parse[i].brandName + " "
  29. + parse[i].companyName + " "
  30. + parse[i].description + " "
  31. + parse[i].id + " "
  32. var htmlSpanElement = document.createElement("p");
  33. htmlSpanElement.innerText = str
  34. document.getElementById("ajax-respone").append( htmlSpanElement )
  35. }
  36. }
  37. }
  38. xmlHttpRequest.open("GET", "<%=request.getContextPath()%>/jsonRequest", true)
  39. xmlHttpRequest.send()
  40. }
  41. </script>
  42. </body>
  43. </html>