Hướng dẫn js fetch post php
Hello guys I just started learning php. So I was trying to make a post request from my javascript file to my php file by Show JavaScript
PHP
Udo E. 2,4712 gold badges18 silver badges28 bronze badges
asked Mar 11 at 17:44
1 You are getting this error: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0, because an HTML error response is being returned to the browser instead of json data. In PHP, use PHP
answered Mar 11 at 19:39
Udo E.Udo E. 2,4712 gold badges18 silver badges28 bronze badges 5 First your js file is missing one curly brace
Also, in your php, you need send back a json something like
1 Nội dung bài viết Fetch api là gì? Trước đây nếu bạn nào đã từng sử dụng XMLHttpRequest để giao tiếp lấy dữ liệu từ
server đến client hay ngược lại thì cũng sẽ hiểu nôm na Fetch api javascript cũng vậy. Fetch api cho phép những nhà phát triển lấy resource và thực hiện những yêu cầu thông qua http. Trước đây chúng tôi có đề cập đến bài viết request api trong Nodejs "3 cách để thực hiện các yêu cầu HTTP (Http request) trong Node.js" nhưng không đề
cập đến thằng này (Fetch) vì sao??? Đoán thử xem nào? Fetch api là gì?Nói cho sang vậy thôi chứ bất cứ thằng lập trình nào mà chẳng biết đến nó (XMLHttpRequest) và sau này sử dụng jquery với ajax để sử dụng post, get... Hồi ajax mới ra, ai mà sử dụng được dụng jquery.ajax cũng là pro lắm rồi. Làm bao nhiêu việc như add html, change value mà không reload lại page, tổ chức các kiểu này nọ. Khiếp lắm, giờ đỡ rồi :D. Sau một thởi gian thì, developers cũng thấy những bất cập khi sử dụng ajax, hay XMLHttpRequest và quay sang ủng hộ native APIs. Và hôm nay, chúng ta cùng đàm đạo về một api đó là fetch. Nhưng khi nói về fetch thì chúng ta cũng nên quên rằng có một api cũng rất mạnh và cũng đang được những lập trình viên sử dụng rộng rãi đó là axios. Nhưng để chỉ ra những điểm khác nhau giữa fetch và aixos thì các bạn nên tìm hiểu kỹ, vì mỗi cái áp dụng khác nhau. Phương thức fetch () nhìn chung rất hiện đại và linh hoạt, chính vì vậy chúng ta sẽ xem qua một số chức năng mà fecth có thể xử lý được. Nhưng lưu ý, fetch() có thể sẽ không được hỗ trợ với các browser cũ, nhưng nhìn chung thì điều đó không đáng bận tâm, vì hầu hết chúng ta đều sử dụng những browser hiện đại hơn. Xem fetch() support browser Cú pháp cơ bản Fetch apilet promise = fetch(url, [options]) * url – the URL to access. * options – optional parameters: method, headers etc. GET Requests with Fetch APIỞ trường hợp nào đó đó chúng ta muốn nhận một json tử một API nào đó, trường hợp này thì gặp nhiều đa số là mấy thằng làm với REST API fetch('https://api.github.com/orgs/nodejs') .then(response => response.json()) .then(data => { console.log(data) // Prints result from `response.json()` in getRequest }) .catch(error => console.error(error)) Custom headersCó thể add headers nếu muốn ví dụ : fetch('https://api.github.com/orgs/nodejs', { headers: new Headers({ 'Content-Type': 'application/json' // 'Content-Type': 'application/x-www-form-urlencoded', }) .then(response => response.json()) .then(data => { console.log(data) }) .catch(error => console.error(error)) Gửi thông tin xác thực với FetchĐể gửi kèm thông tin xác thực cookie (user là ai), chúng ta truyền tham số credentials: include fetch('https://api.github.com/orgs/nodejs', { credentials: 'include', // Useful for including session ID (and, IIRC, authorization headers) }) .then(response => response.json()) .then(data => { console.log(data) // Prints result from `response.json()` }) .catch(error => console.error(error)) Notes: Ở đây ông lập trình nào khi sử dụng credentials: 'include' bị lỗi này "blocked by CORS" thì sử dụng credentials: "same-origin" POST/PUT RequestspostRequest('http://example.com/api/v1/users', {user: 'Dan'}) .then(data => console.log(data)) // Result from the `response.json()` call .catch(error => console.error(error)) function postRequest(url, data) { return fetch(url, { credentials: 'same-origin', // 'include', default: 'omit' method: 'POST', // 'GET', 'PUT', 'DELETE', etc. body: JSON.stringify(data), // Coordinate the body type with 'Content-Type' headers: new Headers({ 'Content-Type': 'application/json' }), }) .then(response => response.json()) } Posting an HTMLpostForm('http://example.com/api/v1/users') .then(data => console.log(data)) .catch(error => console.error(error)) function postForm(url) { const formData = new FormData(document.querySelector('form.edit-user')) return fetch(url, { method: 'POST', // or 'PUT' body: formData // a FormData will automatically set the 'Content-Type' }) .then(response => response.json()) } Form encoded datapostFormData('http://example.com/api/v1/users', {user: 'Mary'}) .then(data => console.log(data)) .catch(error => console.error(error)) function postFormData(url, data) { return fetch(url, { method: 'POST', // 'GET', 'PUT', 'DELETE', etc. body: new URLSearchParams(data), headers: new Headers({ 'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }) }) .then(response => response.json()) } Uploading filespostFile('http://example.com/api/v1/users', 'input[type="file"].avatar') .then(data => console.log(data)) .catch(error => console.error(error)) function postFile(url, fileSelector) { const formData = new FormData() const fileField = document.querySelector(fileSelector) formData.append('username', 'abc123') formData.append('avatar', fileField.files[0]) return fetch(url, { method: 'POST', // 'GET', 'PUT', 'DELETE', etc. body: formData // Coordinate the body type with 'Content-Type' }) .then(response => response.json()) } Uploading multiple filesTrên client là như thế này. input type="file" multiple="" class="files" name="files" Cách sử dụng. postFile('http://example.com/api/v1/users', 'input[type="file"].files') .then(data => console.log(data)) .catch(error => console.error(error)) function postFile(url, fileSelector) { const formData = new FormData() const fileFields = document.querySelectorAll(fileSelector) // Add all files to formData Array.prototype.forEach.call(fileFields.files, f => formData.append('files', f)) // Alternatively for PHP peeps, use `files[]` for the name to support arrays // Array.prototype.forEach.call(fileFields.files, f => formData.append('files[]', f)) return fetch(url, { method: 'POST', // 'GET', 'PUT', 'DELETE', etc. body: formData // Coordinate the body type with 'Content-Type' }) .then(response => response.json()) } Thật ra nói cho hay vậy chứ thấy axios ngon hơn nhiều há há, Để lần sau post về axios rồi so sánh cho anh em một phát. Giờ thì test thử xem nó hay ho thế nào. Anh em nào muốn đọc kỹ hơn thì link đây: https://gist.github.com/justsml/529d0b1ddc5249095ff4b890aad5e801 |