天天看點

AngularJS中的互動 $http

這篇文章,主要是通過我們熟悉的jquery中ajax和jsonp的類型方式,總結一下$http的使用。

$http 是 AngularJS 中的一個核心服務,用于讀取遠端伺服器的資料。

1. angular中的ajax

寫法一:

$http({
    method: 'GET',  //可以改成POST
    url: '/someUrl'
}).then(function successCallback(response) {
        // 請求成功執行代碼
    }, function errorCallback(response) {
        // 請求失敗執行代碼
});
           

示例:

var app = angular.module('myApp', []);    
app.controller('siteCtrl', function($scope, $http) {
    $http({
        method: 'GET',
        url: 'https://www.runoob.com/try/angularjs/data/sites.php',

    }).then(function successCallback(response) {
            console.log(response.data);
        }, function errorCallback(response) {
            console.log('失敗');
    });
});
           

寫法二:

①GET請求

$http.get('/someUrl',config).then(successCallback, errorCallback); 
$http.get('/someUrl',{params:{}}).then(successCallback, errorCallback);
           

示例:

$http.get({
    'http://10.30.24.12/emp-management/empDetail',
    {params:{"id":}}
}).then(function successCallback(response) {
        console.log(response.data.name);
    }, function errorCallback(response) {
        console.log('失敗');
});
           

②POST請求

$http.post('/someUrl', data, config).then(successCallback, errorCallback);
           

示例:

$http({  
    method:'post',  
    url:'post.php',  
    data:{name:"aaa",id:"1",age:"20"}  
}).then(function successCallback(response) {
        console.log(response);
    }, function errorCallback(response) {
        console.log('失敗');
});

//但是,這時候你可能收不到傳回的資料,結果為null,這是因為要轉換成form data。 
//解決方案(在post中進行相應配置):
$http({  
   method:'post',  
   url:'post.php',  
   data:{name:"aaa",id:"1",age:"20"},  
   headers:{'Content-Type': 'application/x-www-form-urlencoded'},  
   transformRequest: function(obj) {  
     var str = [];  
     for(var p in obj){  
       str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));  
     }  
     return str.join("&");  
   }  
}).then(function successCallback(response) {
        console.log(response);
    }, function errorCallback(response) {
        console.log('失敗');
});

/*
原了解讀:
首先,配置headers是因為,POST送出時,使用的Content-Type是application/x-www-form-urlencoded,
而使用原生AJAX的POST請求如果不指定請求頭RequestHeader,預設使用的Content-Type是text/plain;charset=UTF-8,
在html中form的Content-type預設值是Content-type:application/x-www-form-urlencoded,是以要進行相應的配置。
然後,配置transformRequest是因為,如果參數是對象,需要轉化一下。
*/
           

2.angular中的jsonp

$http({method:'JSONP',url:''}).success().error();
$http.jsonp('/someUrl').success().error();

//這裡要注意,跨域請求的url後一定要追加參數callback,并且callback的值是固定的,即JSON_CALLBACK,盡量不要去做任何改動
           

示例:

$http({ 
    method: 'JSONP', 
    url: 'http://www.b.com/test.php?callback=JSON_CALLBACK' 
}).success(function(response){ 
    console.log(response); 
}); 

$http.jsonp(
    'http://www.b.com/test.php?callback=JSON_CALLBACK'
).success(function (response){ 
    console.log(response); 
}); 
           

3.最後,總結一下注意事項:

(1)代碼裡使用的.then()也可以寫成.success().error(),但是v1.5中 $http 的 success 和 error 方法已廢棄,使用 then 方法替代;
(2)關于參數:用GET的時候就是params,用POST/PUT/PATCH/DELETE就是data;
(3)$http.jsonp跨域請求的url後一定要追加參數callback,并且callback的值是固定的,即JSON_CALLBACK,盡量不要去做任何改動。
           

繼續閱讀