axios.jsライブラリの使い方(post)
axios.jsで前回getしてみました。※axios.jsライブラリの使い方(get)
今回はjsonデータをpostしてみます。
postする際のヘッダは、Content-Type:application/x-www-form-urlencoded
になりますが、URLSearchParamsクラスを使用すればそのままJSONデータをpostすることができますと公式サイトに書いています。オレオレ翻訳してます。
URLSearchParamsは未対応のブラウザがあると思いますがChromeでは動作します。(Chrome49から対応しています)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8" /> | |
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> | |
<title>axiosjs</title> | |
</head> | |
<body> | |
<script> | |
var params = new URLSearchParams(); | |
params.append('id', 100); | |
params.append('name', 'takahashi'); | |
axios.post("https://uperworld.com/axiosjs/post01.php", params) | |
.then(ret => alert(ret.data)); | |
</script> | |
</body> | |
</html> |
post先のphpは以下です。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$json_string = file_get_contents('php://input'); | |
echo $json_string; | |
$obj = json_decode($json_string); | |
return $obj; | |
?> |
良きに動いてくれます。

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES6),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^
資格:少額短期保険募集人,FP3級,宅建士
コメント