基本
デモ
HTML
<script src="axios.min.js"></script>
~略~
<input type="button" value="非同期通信" onclick="test1()" class="btn btn-success" />
<div id="res"></div>
JavaScript
function test1(){
var data = {'ise-ebi':'イセエビ'};
var json_str = JSON.stringify(data);
let params = new URLSearchParams();
params.append('key1', json_str);
axios.post('server.php', params)
.then(function (res) {
var output = document.getElementById('res');
if(typeof res.data == 'object'){
output.innerHTML = JSON.stringify(res.data);
}else{
output.innerHTML = res.data;
}
})
.catch(function (err) {
console.log(err);
});
}
PHP(server.php)
<?php
$json_param=$_POST['key1'];
$param=json_decode($json_param,true);//JSON文字を配列に戻す
$data=array('neko'=>'猫','yagi'=>'山羊','kani'=>'蟹','same'=>'鮫');
$data = array_merge ($data,$param);
$json_str = json_encode($data);//JSONに変換
echo $json_str;