Skip to content
Siamcoder

การทำงานกับ AJAX ใน TypeScript

typescript1 min read

เมื่อเราพัฒนาแอปพลิเคชันเว็บใน TypeScript เราอาจต้องติดต่อกับแหล่งข้อมูลหรือบริการภายนอกผ่าน AJAX (Asynchronous JavaScript and XML) เพื่อเรียกข้อมูลโดยอัตโนมัติและอัปเดตหน้าเว็บโดยไม่ต้องรีเฟรชหน้าเว็บทั้งหมด ใน TypeScript เราสามารถใช้งาน AJAX ได้โดยใช้ XMLHttpRequest หรือ Fetch API ซึ่งมีวิธีการใช้งานอยู่ในตัวอย่างดังต่อไปนี้:

// ตัวอย่างการเรียกใช้งาน AJAX ด้วย XMLHttpRequest
// สร้างอ็อบเจกต์ XMLHttpRequest
const xhttp = new XMLHttpRequest();
// กำหนดฟังก์ชันที่จะถูกเรียกเมื่อสถานะการเปลี่ยนแปลง
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
// การดึงข้อมูลจากเซิร์ฟเวอร์
const response = JSON.parse(this.responseText);
console.log(response);
}
};
// กำหนด HTTP method และ URL
xhttp.open("GET", "https://api.example.com/data", true);
// ส่งคำขอ
xhttp.send();
// ตัวอย่างการเรียกใช้งาน AJAX ด้วย Fetch API
// การใช้งาน Fetch API เพื่อดึงข้อมูล
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(error => {
console.log(error);
});`

ในตัวอย่างด้านบน เราใช้ XMLHttpRequest และ Fetch API เพื่อเรียกใช้งาน AJAX ใน TypeScript โดยส่งคำขอ GET ไปยัง URL ที่กำหนด และรับข้อมูลที่ส่งกลับมาจากเซิร์ฟเวอร์เป็น JSON และแสดงผลในคอนโซล

การใช้งาน AJAX ใน TypeScript ช่วยให้เราสามารถปรับปรุงประสิทธิภาพและประสบการณ์ผู้ใช้ของแอปพลิเคชันเว็บได้มากขึ้น โดยไม่ต้องรีเฟรชหน้าเว็บทั้งหมดเมื่อต้องการอัปเดตข้อมูล

นอกจากนี้ยังสามารถใช้งาน AJAX ใน TypeScript เพื่อส่งข้อมูลผ่าน HTTP methods อื่น ๆ เช่น POST, PUT, DELETE ไปยังเซิร์ฟเวอร์เพื่อดำเนินการเพิ่ม แก้ไข หรือลบข้อมูล ตัวอย่างเช่น:

// ตัวอย่างการส่งข้อมูลผ่าน AJAX ด้วย XMLHttpRequest
// สร้างอ็อบเจกต์ XMLHttpRequest
const xhttp = new XMLHttpRequest();
// กำหนดฟังก์ชันที่จะถูกเรียกเมื่อสถานะการเปลี่ยนแปลง
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 201) {
console.log("Data created successfully");
}
};
// กำหนด HTTP method และ URL
xhttp.open("POST", "https://api.example.com/data", true);
// กำหนด header และข้อมูลที่จะส่ง
xhttp.setRequestHeader("Content-Type", "application/json");
const data = {
name: "John",
age: 25
};
// แปลงข้อมูลเป็น JSON และส่งคำขอ
xhttp.send(JSON.stringify(data));
// ตัวอย่างการส่งข้อมูลผ่าน AJAX ด้วย Fetch API
// ข้อมูลที่จะส่ง
const data = {
name: "John",
age: 25
};
// การใช้งาน Fetch API เพื่อส่งข้อมูลแบบ POST
fetch("https://api.example.com/data", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => {
if (response.status === 201) {
console.log("Data created successfully");
}
})
.catch(error => {
console.log(error);
});`

ในตัวอย่างด้านบน เราใช้ XMLHttpRequest และ Fetch API เพื่อส่งข้อมูลแบบ POST ไปยัง URL ที่กำหนด โดยกำหนด header "Content-Type" เป็น "application/json" และแปลงข้อมูลเป็น JSON ก่อนส่งคำขอ หากส่งข้อมูลสำเร็จแล้วจะแสดงผล "Data created successfully" ในคอนโซล