Fetch API เป็นวิธีที่ใช้ทำ ajax แทน XMLHttpRequest (XHR) สามารถใช้ได้กับทุกบราวเซอร์ยกเว้น อ้ายอี (IE) แม้แต่ microsoft edge ก็ยังใช้ได้ แต่จริง ๆ แล้วสามารถบังคับให้อ้ายอีใช้ได้โดยการเรียกใช้ github/fetch ช่วย
ไฟล์กลางที่ไว้ใช้ร่วมกัน
scripts.js /*
pitt phunsanit
default fetch api options
version 1
*/
let fetchOptions = { "headers": { 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }, "method": "post"
}; /*
pitt phunsanit
get status from fetch api
version 1
*/
function fetchStatus (Response) { if (Response.status >= 200 && Response.status < 300) { return Promise.resolve (Response) ; } else { return Promise.reject (new Error (Response.status + ' : ' + Response.statusText)) ; }
}
ตัวอย่างการใช้ fetch แบบ GET
JavaScript/fetch.get.html
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="author" content="Pitt Phunsanit"> <title>fetch: get</title> </head> <body> <script src="../scripts.js"></script> <script>
fetch ('http://localhost/snippets/PHP/json.json_encode.php?name=pitt&surname=phunsanit') .then (fetchStatus) .then (function (response) { response.json () .then (function (data) { alert (JSON.stringify (data)) ; }) ; }) .catch (function (error) { alert (error) ; }) ; </script> </body></html>
เมื่อต้องการส่งข้อมูลแบบ POST ก็เพิ่ม option ไปเล็กน้อย
ตัวอย่างการ fetch แบบ POST
JavaScript/fetch.post.html
<!DOCTYPE html>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="author" content="Pitt Phunsanit"> <title>fetch: post</title> </head> <body> <script src="../scripts.js"></script> <script>
fetchOptions.body = 'email=phunsanit@gmail.com&name=pitt&surname=phunsanit'; fetch ('http://localhost/snippets/PHP/json.json_encode.php', fetchOptions) .then (fetchStatus) .then (function (response) { response.json () .then (function (data) { alert (JSON.stringify (data)) ; }) ; }) .catch (function (error) { alert (error) ; }) ; </script> </body></html>
อ่านเพิ่มเติม