ดึงข้อมูล JSON ด้วย jQuery AJAX

การดึงข้อมูล JSON ด้วย jQuery AJAX ถือว่าเป็นวิธีแบบดั้งเดิม (classic approach) ที่ยังใช้งานได้ดี โดยเฉพาะถ้าโปรเจกต์ของคุณมีการใช้ jQuery อยู่แล้ว

ถ้าโปรเจกต์ของคุณใช้ jQuery อยู่แล้ว (เช่น ASP.NET WebForms) การใช้ $.ajax หรือ $.getJSON จะสะดวกมาก

และนี่คือโค้ดตัวอย่างการดึงข้อมูลจาก JSON มาแสดงอย่างง่าย


ในส่วน tag html

<h2>Posts</h2>
 <ul id="postList"></ul>


ในส่วนของ Script

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function () {
      $.ajax({
        url: "https://jsonplaceholder.typicode.com/posts", // sample JSON API
        type: "GET",
        dataType: "json", // expect JSON response
        success: function (data) {
          // Loop through JSON and append to list
          $.each(data.slice(0, 5), function (index, item) {
            $("#postList").append("<li>" + item.title + "</li>");
          });
        },
        error: function (xhr, status, error) {
          console.error("AJAX Error:", status, error);
        }
      });
    });
  </script>

 JQuery Tutorial
 HTML, JavaScript, JSON, Ajax, JQuery
 2025-12-05 09:35:29