对于想了解AngularJS发送异步Get/Post请求的读者,本文将提供新的信息,我们将详细介绍angular异步请求方式,并且为您提供关于angular$q封装$httpget和post请求、an
对于想了解AngularJS发送异步Get/Post请求的读者,本文将提供新的信息,我们将详细介绍angular异步请求方式,并且为您提供关于angular $q封装$http get和post请求、angular js $post,$get请求传值、Angular JS POST请求未发送JSON数据、AngularJS $http模块POST请求实现的有价值信息。
本文目录一览:- AngularJS发送异步Get/Post请求(angular异步请求方式)
- angular $q封装$http get和post请求
- angular js $post,$get请求传值
- Angular JS POST请求未发送JSON数据
- AngularJS $http模块POST请求实现
AngularJS发送异步Get/Post请求(angular异步请求方式)
AngularJS发送异步Get/Post请求
1 . 在页面中加入AngularJS并为页面绑定ng-app 和 ng-controller
<body ng-app="MyApp" ng-controller="MyCtrl" > ... <script src="js/angular.min.js"></script> <script src="js/sbt.js"></script>
2 . 添加必要的控件并绑定相应的事件
get:<input type="text" ng-model="param">{{param}} <br> post: <input type="text" ng-model="user.name"><input type="text" ng-model="user.password"><br> <button ng-click="get()">Get</button> <button ng-click="post()">Post</button>
3 . 在JS脚本中发送进行Get/Post请求
- get
$scope.get = function () { $http.get("/get",{params: {param: $scope.param}}) .success(function (data,header,config,status) { console.log(data); }) .error(function (data,status) { console.log(data); }) ; }
- post
$scope.post = function () { $http.post("/post",$scope.user) .success(function (data,status) { console.log(data); }) ; }
4 . 由Controller处理请求并返回结果
- get
@RequestMapping("/get") @ResponseBody public Map<String,String> get(String param) { System.out.println("param:"+param); response.put("state","success");//将数据放在Map对象中 return response; }
- post
@RequestMapping("/post2") @ResponseBody public void post2(@RequestBody User user,HttpServletResponse resp) { //返回不同的http状态 if(user.getName()!=null&&!user.getName().equals("")){ resp.setStatus(200); } else{ resp.setStatus(300); } }
5 . 由JS http请求的回调函数处理并执行下一步操作
- HTML
<!DOCTYPE html> <html lang="en"> <head> <Meta charset="UTF-8"> <title>Request</title> </head> <body ng-app="MyApp" ng-controller="MyCtrl" > get:<input type="text" ng-model="param"><br> post: <input type="text" ng-model="user.name"><input type="text" ng-model="user.password"><br> <button ng-click="get()">Get</button> <button ng-click="post()">Post</button> </body> <script src="js/angular.min.js"></script> <script src="js/sbt.js"></script> </html>
- sbt.js
var app = angular.module("MyApp",[]); app.controller("MyCtrl",function ($scope,$http) { $scope.get = function () { $http.get("/get",status) { console.log(data); }) .error(function (response) { console.log(response); }) ; } $scope.post = function () { $http.post("/post",status) { console.log(data); }) ; } });
angular $q封装$http get和post请求
//第一步,定义发送请求的配置信息
angular.module('hkApp') .constant('API_ENDPOINT',{ host: 'http://testfx.ypcoo.com',port: 80,path: '/index.PHP/Wap',platform: 'weixin' // string 'weixin or app' 平台常量,通过此参数判断系统是在微信里面使用还是在APP里面使用,以便调用不同的微信接口 });
//第二步,定义一个服务,“专门”用来发送get或者post请求
/** * 定义ApiService服务 * 功能:专门向服务器发送post 和 get请求 * */ angular.module('hkApp') .factory('ApiService',["$window","$http","WAP_CONfig","$q","$log","$ionicLoading",function($window,$http,WAP_CONfig,$q,$log,$ionicLoading) { var _api = WAP_CONfig; var endpoint = _api.host + ':' + _api.port; // public api return { //发送服务器的域名+端口,例如http://deve.sqhzg.cn:80 endpoint: endpoint,//post请求,第一个参数是URL,第二个参数是向服务器发送的参数(JSON对象), post: function(url,data) { url = endpoint + url; var deferred = $q.defer(); var tempPromise; //显示加载进度 $ionicLoading.show({ template: 'Loading...' }); //判断用户是否传递了参数,如果有参数需要传递参数 if(data != null && data != undefined && data != ""){ tempPromise = $http.post(url,data); }else{ tempPromise = $http.post(url); } tempPromise.success(function(data,header,config,status) { deferred.resolve(data); $ionicLoading.hide(); }).error(function(msg,code) { deferred.reject(msg); $log.error(msg,code); $ionicLoading.hide(); }); return deferred.promise; },//get请求,第一个参数是URL,第二个参数是向服务器发送的参数(JSON对象), get: function(url,data) { url = endpoint + url; var deferred = $q.defer(); var tempPromise; //显示加载进度 $ionicLoading.show({ template: 'Loading...' }); //判断用户是否传递了参数,如果有参数需要传递参数 if(data != null && data != undefined && data != ""){ tempPromise = $http.get(url,data); }else{ tempPromise = $http.get(url); } tempPromise.success(function(data,code) { deferred.reject(msg); $ionicLoading.hide(); $log.error(msg,code); }); return deferred.promise; } }; }]);
备注:在请求前添加了$ionicLoading显示,请求返回之后,因此$ionicLoading对象。当遇到服务器压力大的时候,不会出现“白屏” 的情况,提高用户体验
//控制器注入服务,发送请求
.state('index',{ url:'/app_index',templateURL: 'ABC.html',onEnter :function(){ //因此底部的导航栏 $(".index_footer").show(); },controller:["$scope","$state",'$ionicActionSheet',"setting_user_levelService","userNameService","ApiService",function($scope,$state,$ionicActionSheet,setting_user_levelService,userNameService,ApiService){ //获取用户信息 var userInfoPromise = ApiService.post("{:U('UserInfo/getUser')}",{ "id": "{$Think.session.ADMINID}" }); userInfoPromise.then(function(response){ if(response.status == 1){ //会员名称 $scope.typetext = response.data.typetext; //积分 $scope.jifen = response.data.jifen; //红包 $scope.redpacket = response.data.redpacket; } }); }] })
angular js $post,$get请求传值
困扰了我好几天的问题!!!
刚开始学play框架,在向后台传值时,一直不成功!
当你用$POST传递一个参数时:
HTML:
<button ng-click=test()>测试</button>
JS:
①
$scope.test = function() {
$http({
method: ''POST'',
url: ''/Application/jump'',
data:{name:"zby"},
}).then(function successCallback(response) {
// 请求成功执行代码
}, function errorCallback(response) {
// 请求失败执行代码
});
}
我的后台控制器方法:
public static void test(String name) {
System.out.println(name);
System.out.println(params.get("name"));
}
这样传到后台的值为NULL,NULL。
我把JS换成:
②
$scope.test = function() {
$http({
method: ''POST'',
url: ''/Application/test'',
params: {name:"zby"},
}).then(function successCallback(response) {
// 请求成功执行代码
}, function errorCallback(response) {
// 请求失败执行代码
});
}
后台控制器方法不变。
传到后台的值为zby,zby。
同理传递多个参数也能成功,只要把JS里的params与后台控制器的test的参数改成多个就行,但是两个参数名字,个数必须一致。
还有一种方法则是把传递的值直接写入URL里,把JS改成
③
$scope.test = function() {
var name = "zby";
$http({
method: ''POST'',
url: ''/Application/test?name='' + name,
}).then(function successCallback(response) {
// 请求成功执行代码
}, function errorCallback(response) {
// 请求失败执行代码
});
}
后台控制器方法不变,照样能接收到后台传来的值。
接下来看看$get方法传值:
①方法传到后台的值与$post一样为NULL,NULL。
②方法传到后台的值与$post一样为zby,zby。
③方法传到后台的值与$post一样为zby,zby。
所以能看出来这三种方法$post,$get传值都一样。
接下来我们看看第四种方法
④
$scope.test = function() {
$http({
method: ''POST'',
url: ''/Application/test'',
data: {name: "zby"},
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) {
// 请求成功执行代码
}, function errorCallback(response) {
// 请求失败执行代码
});
}
后台控制器方法不变,传递到后台的值为zby,zby。
那么我们看看这种方法GET请求行不行,将JS里的method改为method: ''GET'',传递到后台的值为NULL,NULL。
$get请求并不能用这种方法传递,而$post确可以。这是为什么呢?
来看看这四种方法的request请求到底发了啥数据过来
第①种:
$post
$get
第②种:
$post
$get
第③种:
$post
$get
第④种:
$post:
$get:
通过测试可知,
在第②种方法与第③种方法中,$post与$get请求都能够向后台传值,并且通过图的比较可知都是通过Query String Parameters传值
在第①种方法中,$post与$get请求不能向后台传值,但是$post请求的图中多出了
在第④种方法中,$get请求不能向后台传值,而$post请求能向后台传值,并且第①种与第④种的区别在于第④种方法添加了如下代码:
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("&");
}
为什么加了这段代码$post请求就可以传值成功了呢?
我们看看两种的区别:
①:
④:
可以发现AngularJs用post 提交数据 以 json 格式提交的,而平时我们jquery post 提交数据是以 form-data 的形式提交的,只有把它转化为form-data形式后台才能接收到。
解决方法就是:改AngularJs 提交数据的方式,配置 header 值,使用 transformRequest对提交数据进行序列化,把 json 对象更改为字符串。
Angular JS POST请求未发送JSON数据
如何解决Angular JS POST请求未发送JSON数据?
如果你要序列化数据对象,那么它将不是正确的json对象。充分利用现有内容,然后将数据对象包装在中JSON.stringify()。
$http({
url: ''/user_to_itsr'',
method: "POST",
data: JSON.stringify({application:app, from:d1, to:d2}),
headers: {''Content-Type'': ''application/json''}
}).success(function (data, status, headers, config) {
$scope.users = data.users; // assign $scope.persons here as promise is resolved here
}).error(function (data, status, headers, config) {
$scope.status = status + '' '' + headers;
});
解决方法
我正在尝试将一个对象作为JSON发送到Flask中的Web服务,该对象期望请求数据中包含JSON。
我已经通过发送JSON数据手动测试了该服务,并且工作正常。但是,当我尝试通过角度控制器发出http POST请求时,Web服务器向我发送一条消息,说它未接收到JSON。
当我检查Chrome中的请求标头时,似乎不是以JSON格式发送数据,而是通过内容类型将常规键/值对设置为application / json
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json,text/plain,/
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:49
Content-Type:application/json;charset=UTF-8
DNT:1
Host:localhost:5000
Origin:http://localhost:5000
Referer:http://localhost:5000/
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/27.0.1453.116 Safari/537.36
X-Requested-With:XMLHttpRequest
Request Payload
application=AirFare&d1=10-APR-2013&d2=14-APR-2013
如果您看到了请求有效载荷下面的最后一行,则可以看到数据不是JSON格式。
这是我的角度控制器中的HTTP POST调用:
$http({
url: ‘/user_to_itsr’,
method: “POST”,
data: {application:app,from:d1,to:d2},
headers: {‘Content-Type’: ‘application/json’}
}).success(function (data,status,headers,config) {
$scope.users = data.users; // assign $scope.persons here as promise is resolved here
}).error(function (data,config) {
$scope.status = status + ‘ ‘ + headers;
});
};
我将数据作为对象{}发送,但是在JSON.stringify进行序列化之后,我尝试发送数据,但是,我似乎没有任何操作将JSON发送到服务器。
真的很感谢有人能帮忙。
AngularJS $http模块POST请求实现
一、代码如下:
$http({ method:''post'', url:''post.php'', data:{name:"aaa",id:1,age:20} }).success(function(req){ console.log(req); })
解决方案:
1、
var myApp = angular.module(''app'',[]); myApp.config(function($httpProvider){ $httpProvider.defaults.transformRequest = function(obj){ var str = []; for(var p in obj){ str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); } return str.join("&");
2.
$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("&"); } }).success(function(req){ console.log(req); })
php
$rawpostdata = file_get_contents("php://input"); $post = json_decode($rawpostdata, true); //传的数据都在$post中了;
二、 $http请求数据主要会有以下三种方式
1.get请求
2.post请求
3.jsonp
<!DOCTYPE html> <html lang="zh_CN"> <head> <meta charset="UTF-8"> <title>Angular基础</title> </head> <body> <div ng-app="myApp"> <div ng-controller="personCtrl"> 姓:<input type="text" ng-model="firstName"/><br/> 名:<input type="text" ng-model="lastName"/><br/> 姓名:<span ng-bind="firstName"></span><span ng-bind="lastName"></span> </div> </div> <script src="angular.min.js"></script> <script type="application/javascript"> var myApp=angular.module(''myApp'',[]); myApp.controller(''personCtrl'',function($scope,$http){ $http.get(''getData.php''). success(function(data) { console.log(data); }). error(function(err) { //错误代码 }); //$http.post采用postJSON方式发送数据到后台, // 解决办法:在后台php中使用$postData=file_get_contents("php://input",true);这样就可以获得前端传送过来的数据 var postData={msg:''post的内容''}; var config={params:{id:''5'',name:''张三丰''}}; $http.post(''postData.php'', postData,config). success(function(data) { console.log(data); }). error(function(err) { //错误代码 }); var myUrl ="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSON_CALLBACK"; $http.jsonp(myUrl).success( function(data){ console.log(data); } ).error(function(err){ //错误代码 }); $scope.firstName="Wang"; $scope.lastName="Ben"; }); </script> </body> </html>
<?php //postData.php文件 //用接收json数据的方式 $msg=file_get_contents("php://input",true); $name=$_GET[''name'']; echo $name.$msg."_post";
显示效果:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
- 解决angular的$http.post()提交数据时后台接收不到参数值问题的方法
- 对比分析AngularJS中的$http.post与jQuery.post的区别
- Angularjs中$http以post请求通过消息体传递参数的实现方法
- 后端接收不到AngularJs中$http.post发送的数据原因分析及解决办法
- AngularJS下$http服务Post方法传递json参数的实例
- AngularJS $http post 传递参数数据的方法
- angularJS 发起$http.post和$http.get请求的实现方法
- AngularJS封装$http.post()实例详解
- 深入理解Angularjs中$http.post与$.post
- Angular利用HTTP POST下载流文件的步骤记录
关于AngularJS发送异步Get/Post请求和angular异步请求方式的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于angular $q封装$http get和post请求、angular js $post,$get请求传值、Angular JS POST请求未发送JSON数据、AngularJS $http模块POST请求实现等相关知识的信息别忘了在本站进行查找喔。
本文标签: