9
9

More than 5 years have passed since last update.

AngularJSで$httpを利用して、Ajaxでサーバ通信

Last updated at Posted at 2013-12-25

AngularJSで$httpを利用して、Ajaxでサーバと通信する。

基本形

コントローラの引数に$httpが必要となる。

function TodoCtr($scope,$http){
    $scope.hello = function() {
         $http({method: 'GET',
               url: 'http://localhost:8080/api/angular'
          ).
          success(function(data, status, headers, config) {
             alert(date); 
          }).
          error(function(data, status, headers, config) {
             alert(status);
          });
    }

パラメータあり

オブジェクトをparams引数に設定すると、URLの後ろにkey=valueの形式で付与される。
以下の例だと、「http://localhost:8080/api/angular?aaa=111&bbb=222」となる。

function TodoCtr($scope,$http){
    $scope.hello = function() {

        var parameter = {
                        aaa:"111",
                        bbb:"222"
        }

         $http({method: 'GET',
               url: 'http://localhost:8080/api/angular',
               params: parameter}
          ).
          success(function(data, status, headers, config) {
             alert(date); 
          }).
          error(function(data, status, headers, config) {
             alert(status);
          });
    }

$httpの中で、encodeURIComponentが行われているので、マルチバイトの場合も気を使う必要はなし。

9
9
1

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
9
9