Tag: ajax

  • รู้จักเอแจ๊กซ์ (AJAX) และการใช้งาน

    AJAX ย่อมาจากคำว่า Asynchronous JavaScript and XML ซึ่งหมายถึงการพัฒนาเว็บแอพพลิเคชั่นที่ประมวลผลในเบื้องหลังเป็นเทคนิคในการพัฒนาเว็บแอปพลิเคชันเพื่อให้สามารถโต้ตอบกับผู้ใช้ได้ดีขึ้น ทำให้ความรู้สึกการใช้งานโปรแกรมเหมือนกับเดสก์ท็อปแอปพลิเคชัน

    ปกติแล้วในภาษาสคริปต์ที่ใช้งานกับเว็บไซต์จะมีการทำงานประมวลผลแบบเป็นลำดับ (synchronous) โดยที่คำสั่งแรกจะต้องประมวลผลให้เสร็จสิ้นก่อนแล้วถึงจะทำงานในคำสั่งถัดไป แต่กระบวนการทำงานแบบเอแจ๊กซ์เมื่อบราวเซอร์ (Browser) ร้องขอข้อมูลไปยังเซิร์ฟเวอร์ (Server) บราวเซอร์จะไปทำงานคำสั่งถัดไปทันที (asynchronous) โดยที่ไม่ต้องรอการตอบกลับจากเซิร์ฟเวอร์ก่อน

    ทำให้การตอบสนองต่อผู้ใช้งานดูรวดเร็วขึ้น และเมื่อเซิร์ฟเวอร์ประมวลผลเสร็จแล้วถึงจะส่งข้อมูลกลับมาที่เอแจ๊กซ์และให้เอแจ๊กซ์ทำงานกับข้อมูลที่ส่งกลับมาอีกทีซึ่งสามารถเขียนโค้คการทำงานดังนี้

    ตัวอย่างโค้คการทำงาน AJAX ของโดยใช้ jQuery

    $.ajax({
        	type: 'GET',
        	url: 'send-ajax-data.php',
        	dataType: "JSON", // data type expected from server
        	success: function (data) {
               	console.log(data);
        	},
        	error: function(error) {
               	console.log('Error: ' + error);
        	}
    });
    

    และปัจจุบันในการเขียน JavaScript เพื่อเรียกใช้งาน AJAX นั้นเราไม่จำเป็นต้องพึ่งพา jQuery อีกต่อไปแล้วซึ่งสามารถเขียนโค้ดการทำงานได้ดังนี้

    วิธีที่ 1  ใช้ XMLHttpRequest [1]

    var request = new XMLHttpRequest();
    request.open('GET','https://tutorialzine.com/misc/files/my_url.html', true);
    
    request.onload = function (e) {
        if (request.readyState === 4) {
    
            // Check if the get was successful
            if (request.status === 200) {
                console.log(request.responseText);
            } else {
                console.error(request.statusText);
            }
        }
    };
    
    // Catch errors:
    request.onerror = function (e) {
        console.error(request.statusText);
    };
    
    request.send(null);
    

    วิธีที่ 2 ใช้ Fetch API [2]

    fetch('./api/some.json')
      .then(
        function(response) {
          if (response.status !== 200) {
            console.log('Looks like there was a problem. Status Code:' +
     response.status);
            return;
          }
    
          // Examine the text in the response
          response.json().then(function(data) {
            console.log(data);
          });
        }
      )
      .catch(function(err) {
        console.log('Fetch Error :-S', err);
      });
    

    อ้างอิง:

    https://tutorialzine.com/2014/06/10-tips-for-writing-javascript-without-jquery [1]

    https://developers.google.com/web/updates/2015/03/introduction-to-fetch [2]

    https://www.javascripttutorial.net/javascript-fetch-api/  

    วิดีโอ: https://www.youtube.com/watch?v=F1TECaRf-uA&feature=youtu.be&t=2375