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

วิธีระบุ HTTP Method สำหรับส่งข้อมูลฟอร์มใน HTML

ใช้แอตทริบิวต์ method ในแท็ก <form> เพื่อระบุวิธี HTTP ที่ใช้ส่งข้อมูลฟอร์ม

ตัวอย่าง

ลองใช้โค้ดต่อไปนี้เพื่อใช้งานแอตทริบิวต์ method:

<!DOCTYPE html>
<html>
  <head>
    <title>HTML Form Method</title>
  </head>
  <body>
    <form action="/cgi-bin/dropdown.cgi" method="post">
      <select name="dropdown">
        <option value="HTML" selected>HTML</option>
        <option value="Ruby">Ruby</option>
      </select>
      <input type="submit" value="Submit" />
    </form>
  </body>
</html>

ค่าของ method attribute

ค่า HTTP Method คำอธิบาย กรณีใช้งาน
get GET ส่งข้อมูลผ่าน URL Query String (?key=value&...) ค้นหา, Filter, Pagination, Idempotent actions
post POST ส่งข้อมูลใน Request Body (ปลอดภัยกว่า, ไม่มีขนาดจำกัด) Login, Register, Create/Update/Delete data, Sensitive data
dialog - ปิด Dialog (<dialog>) ไม่ส่งข้อมูลไป Server Modal dialog forms

ความแตกต่าง GET vs POST

ด้านเปรียบเทียบ GET POST
ข้อมูลปรากฏใน URL ใช่ (Query string) ไม่ (Request body)
Bookmark/Share ได้ ได้ ไม่ได้
ขนาดข้อมูล จำกัด (~2000 chars) ไม่จำกัด (ขึ้นกับ server config)
Cache ได้ ได้ ไม่ได้
History อยู่ใน History ไม่อยู่ (Browser 警告 resubmit)
ความปลอดภัย สูงกว่า (ไม่เห็นใน URL)
Idempotent ควรเป็น (Safe) ไม่จำเป็น

แอตทริบิวต์ formmethod (HTML5)

สามารถ override method ได้ต่อปุ่ม Submit:

<form action="/search" method="get">
  <input type="search" name="q">
  <button type="submit">Search (GET)</button>
  <button type="submit" formmethod="post" formaction="/search/post">
    Advanced Search (POST)</button>
</form>

Enctype สำหรับ POST

<!-- Default: application/x-www-form-urlencoded -->
<form method="post">...</form>

<!-- สำหรับ File Upload (จำเป็น) -->
<form method="post" enctype="multipart/form-data">
  <input type="file" name="avatar">
</form>

<!-- สำหรับ JSON (ใช้ JS ส่ง) -->
<form method="post" enctype="text/plain">...</form>