Fetch API เป็นวิธีที่ใช้ทำ ajax แทน XMLHttpRequest (XHR) สามารถใช้ได้กับทุกบราวเซอร์ยกเว้น อ้ายอี (IE) แม้แต่ microsoft edge ก็ยังใช้ได้ แต่จริงๆ แล้วสามารถบังคับให้อ้ายอีใช้ได้โดยการเรียกใช้ github/fetch ช่วย
ไฟล์กลางที่ไว้ใช้ร่วมกัน
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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> .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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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> |
อ่านเพิ่มเติม