Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

JavaScript alert(): คู่มือการใช้งาน Dialog Box แจ้งเตือน

เมธอด JavaScript alert() (หรือ Window.alert()) แสดง alert dialog box ให้ผู้ใช้ รับ optional message argument แสดงข้อความพร้อมปุ่ม OK ใช้บ่อยสำหรับแจ้ง success, errors

alert() ยังใช้เป็น development tool ได้ เช่นวางใน function handle form submission หลัง event.preventDefault() (event.preventDefault() ยกเลิก default behavior redirect หลังกด submit)

JavaScript alert() คืออะไร?

alert() แสดง pop-up dialog box ส่ง message string optional ได้ custom message สำคัญ: alert() ควรใช้เฉพาะข้อความที่ต้องการ acknowledgement (กด OK) ไม่ควรใช้สำหรับข้อความที่ต้องการ action

ใช้ได้หลายอย่าง: แสดง success/error ใน fetch request, debug program flow ใน function

Syntax

alert('message'); // แสดง dialog กล่องข้อความ "message"
alert(); // ไม่ส่ง message: dialog ว่างเปล่าพร้อมปุ่ม OK

ตัวอย่างการใช้งาน

1. Developer Side: Debug Form Submission

Form login พื้นฐาน:

<form>
  <label>Name</label> <input type="text" name="name">
  <label>Password</label> <input type="text" name="name">
  <button type="submit">Log In</button>
</form>

Function handle submit:

const handleOnSubmit = (event) => {
  event.preventDefault();
  alert("Logged In");
}

ผูกกับ form:

<form onSubmit="handleOnSubmit(event)"> ... </form>

กด Login -> dialog "Logged In" แสดง -> ทราบว่า function communicate กับ form ได้

2. Client Side: แสดง Error ใน Fetch Request

fetch('/current-cart/', {
  credentials: 'include', method: 'GET',
  headers: { 'Content-Type': 'application/json' }
})
.then(resp => resp.json())
.then(cart => {
  if (cart.error) { alert(cart.error); }
});

Shopping cart fetch request ถ้าไม่มี active cart -> alert error

3. Form Validation Errors

fetch('/login', {
  credentials: 'include', method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(creds)
})
.then(resp => resp.json())
.then(response => {
  if (response.error) { alert(response.error); }
});

Login form validation: ไม่กรอกฟิลด์ -> alert แสดง validation errors

สรุป

alert() method เรียบง่าย มีหลายใช้งาน รับ optional message string แสดง dialog พร้อม OK button จำไว้: alert() แค่แสดงข้อความ ไม่สามารถ action ได้

ตัวอย่าง: 1) dev side debug form-function communication 2) fetch request errors (dev) 3) form validation errors (user-facing) ลองใช้ใน project ถัดไปสำหรับ test functionalities