我正在使用AngularJS。我想通过AngularJS在HTTP帖子中发送多个数据。后端运行Cakephp,我已经验证Rest API通过python HTTP-post起作用。
我有一个看起来像这样的控制器;
angular.module('myApp.controllers', []).
controller('AlertDemoCtrl', ['$http', function($http)
{
var post_url;
var post_data;
post_url="http://127.0.0.1/api_XXX/";
post_data = {'data[Table1][field1]':'XX',
'data[Table2][0][field1]':'AA',
'data[Table2][0][field2]':'BB',
'data[Table2][0][field3]':'CC'
};
$http.post(post_url, post_data);
}])
当我运行代码时,页面无法正确加载AngularJS。如果我不评论$http.post(post_url, post_data);
,代码将正常运行。我哪里做错了?
非常感谢你。
这里有两件事:
首先,$http
通过AngularJS中的Promises处理对请求的响应。如果您打算对服务器返回的响应进行处理,则应尝试在代码中添加Promise处理。摘自AngularJS官方文档(v1.3.0)
// Simple POST request example (passing data) :
$http.post(post_url, post_data).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
其次,您可以尝试将$http
调用封装在一个函数中,然后在加载页面的整个AngularJS后在事件上调用该函数。
angular.module('myApp.controllers', []).
controller('AlertDemoCtrl', ['$http', function($http)
{
var post_url;
var post_data;
post_url="http://127.0.0.1/api_XXX/";
post_data = {'data[Table1][field1]':'XX',
'data[Table2][0][field1]':'AA',
'data[Table2][0][field2]':'BB',
'data[Table2][0][field3]':'CC'
};
$scope.fetch = function() {
$http.post(post_url, post_data).success(function() {
// handle response here
}).error(function() {
// handle error here
});
}
}])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句