国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

AngularJS中$http的交互問題

2024-05-06 15:19:18
字體:
供稿:網(wǎng)友

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

$http 是 AngularJS 中的一個核心服務(wù),用于讀取遠(yuǎn)程服務(wù)器的數(shù)據(jù)。

1. angular中的ajax

寫法一:

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

示例:

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":3}}}).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('失敗');});//但是,這時候你可能收不到返回的數(shù)據(jù),結(jié)果為null,這是因為要轉(zhuǎn)換成form data。 //解決方案(在post中進(jìn)行相應(yīng)配置):$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,默認(rèn)使用的Content-Type是text/plain;charset=UTF-8,在html中form的Content-type默認(rèn)值是Content-type:application/x-www-form-urlencoded,所以要進(jìn)行相應(yīng)的配置。然后,配置transformRequest是因為,如果參數(shù)是對象,需要轉(zhuǎn)化一下。*/

2.angular中的jsonp

$http({method:'JSONP',url:''}).success().error();$http.jsonp('/someUrl').success().error();//這里要注意,跨域請求的url后一定要追加參數(shù)callback,并且callback的值是固定的,即JSON_CALLBACK,盡量不要去做任何改動            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 怀来县| 福贡县| 确山县| 石家庄市| 蕲春县| 扬中市| 泾阳县| 翁牛特旗| 张家口市| 龙州县| 通辽市| 湾仔区| 宿松县| 迁安市| 阜南县| 汶上县| 莱州市| 邹城市| 赣榆县| 安西县| 延川县| 石家庄市| 荃湾区| 定襄县| 雅安市| 龙南县| 乃东县| 芒康县| 汉阴县| 叶城县| 武清区| 井陉县| 湖南省| 泰和县| 泾川县| 淮安市| 永州市| 金阳县| 安陆市| 衡南县| 南昌市|