$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('失败');
});
});
$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('失败');
});
$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是因为,如果参数是对象,需要转化一下。
*/
$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);
});
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有