LoginSignup
1
0

More than 5 years have passed since last update.

Angular JSを使ってhttp通信

Last updated at Posted at 2018-11-21

Angular JSで非同期通信

前提:AngularJSが環境で使える.phpの環境が整っている

前回のAngular js でストップウォッチを作ったメモでユーザ側からのアクション(ボタンクリック)をcsvに書き出すためにhttp通信を使った.

流れは

  1. ボタンの中で定義したng-onclickに対して、hogeというイベントリスナーを呼び出す
  2. 呼び出したイベントリスナーの中にphp呼び出すスクリプトを書く
  3. 呼び出されたphpスクリプトがJS側からのデータを受け取り,サーバサイドの処理をする.

という感じ
ログをとったり,同一ページで動的にページを更新して行ったりするときに使う

まずはhtmlから

test.html
<html ng-app="app">
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.5/angular.min.js"></script>
        <script src="./Control.js"></script>
    </head>
    <body>
        <div ng-controller="hoge">
            <input type="button"ng-click="hogehoge(1)" value="1">
            <input type="button"ng-click="hogehoge(2)" value="2">
            <input type="button"ng-click="hogehoge(3)" value="3">
            <input type="button"ng-click="hogehoge(4)" value="4">
        </div>
    </body>
</html>

http通信のコードは

Control.js
var test = angular.module("app",[]);

test.controller("hoge",function($scope,$http){
    // イベントリスナー定義
    $scope.hogehoge = function(val){
        var data;
        data = { value: val };
        // ここから通信
        $http({
            method: "post",
            url: "proc.php",
            data: data
        }).then(function DoneCallback(res){
            console.log(res)
        },function failCallback(res){
            console.log(res)
        });
    };
})

とまあこんな感じ

最後にphp

proc.php
<?php
$val = json_decode(file_get_contents("php://input"),TRUE);
file_put_contents("./test.csv",$val["value"]);
?>

これでボタンが押されたと同時にcsvに書き出しができるようになりました.
jQueryと大きく異なった点はjQueryは$_POSTで取得ができたのにAngularJSはfile_get_contentsでしか取得ができない点でハマった.
あとcontrollerの呼び出し引数のところで$httpも忘れずに..

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0