fetch API
IEを除くほぼすべてのブラウザで有効
基本的な使い方(GET)
fetch('/fetch?cohai')
.then(response => {
return response.json(); // Promiseを返す
})
.then(data => { // JSONデータ
console.log(data);
})
.catch(error => { // エラーの場合
console.log(error);
});
//textとして取得したい場合
fetch(url)
.then(response => {
return response.text();
})
.then(text => {
console.log(text);
this.name = text;
});
省略形
fetch(url)
.then(res=> res.text() )
.then( text=> console.log(text) );
パラメーターを送信する(POST, PUT, DELETE)
exec: function(){
let data = {name:this.name, age:this.age};
fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(data => {
console.log(data);
this.lists = data;
})
.catch(error => {
console.log(error);
});
}
参考 axios不要!fetch()でAjax通信する方法 fetchを利用する[GET][POST]
PHP
<?php
switch ($_SERVER['REQUEST_METHOD']){
case 'GET' :
$data = array(
'name'=>'mido',
'age'=>'40'
);
echo json_encode($data);
break;
case 'POST' :
$params = json_decode(file_get_contents('php://input'), true);
//処理
echo json_encode($params);
break;
case 'PUT' :
$params = json_decode(file_get_contents('php://input'), true);
//処理
echo json_encode($params);
break;
case 'DELETE' :
$params = json_decode(file_get_contents('php://input'), true);
//処理
echo json_encode($params);
break;
}
?>