Skip to content

Instantly share code, notes, and snippets.

@tranquangchau
Last active April 17, 2018 05:10
Show Gist options
  • Save tranquangchau/7c07dda6efba7f6ef97c719bc32e951c to your computer and use it in GitHub Desktop.
Save tranquangchau/7c07dda6efba7f6ef97c719bc32e951c to your computer and use it in GitHub Desktop.
fetch get and post of javascript
<?php
var_dump($_POST);die;
function postData(url, data) {
// Default options are marked with *
data = Object.keys(data).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])).join('&')
return fetch(url, {
// body:data,
body: (data), // must match 'Content-Type' header
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, same-origin, *omit
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // *client, no-referrer
})
.then(response => response.json()) // parses response to JSON
}
//this.newUser
//object
//newUser.name='csf',
//newUser.age=2
this.postData('index.php',
// {
// answer: 42,
// data:JSON.stringify(this.newUser),
//},
this.newUser
)
//method get jsut basic
fetch('index_data.php')
.then(res => res.json())
.then(res => {
this.cats = res;
})
//more
//https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
//https://github.com/matthew-andrews/isomorphic-fetch/issues/30
////https://stackoverflow.com/a/45345813/3633498
//https://github.github.io/fetch/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment