在 AngularJS 中将数组发送到服务器
Sending array to server in AngularJS
我开始构建 Web 应用程序。
用户可以select向水果列表中添加项目。水果对象列表存储在 Javascript/AngularJS.
中的数组中
当用户按下提交按钮时,我希望将整个水果列表发送到服务器,然后将列表保存到数据库中。
我对HTTP只有一个基本的了解。我想要 POST 数组吗?我该怎么做?
这是一个 POST 示例,它向服务器发送一组水果。此代码将位于您的按钮点击功能内。
$scope.fruit = [{name: 'Apple'}, {name: 'Grape'}];
// Simple POST request example (passing data) :
$http.post('/someUrl', {fruit: $scope.fruit}).
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 的 angular 文档。这应该能帮到你。
我希望你选择 $resource,它包含在 ngResource
模块中。
在 post 调用中传递数组时,您需要在 $resource
选项
中将 isArray
选项提到 true
代码
angular.module('app',[])
//factory will have resource object
.factory('myService',function($resource){
var postFruitData = function(){
return $resource('/savefruit', {}, {saveData: {method:'POST', isArray: true}});
}
return{
saveData: postFruitData
}
})
.controller('mainCtrl',function($scope,myService){
//this function needs to be call on post like form ng-submit
$scope.postFruitData = function(){
myService.saveData({}, $scope.data).$promise.then(function(data){
//you will get data here
});
}
});
有关更多信息,您还可以查看此 SO Question
希望对您有所帮助。谢谢。
我开始构建 Web 应用程序。
用户可以select向水果列表中添加项目。水果对象列表存储在 Javascript/AngularJS.
中的数组中当用户按下提交按钮时,我希望将整个水果列表发送到服务器,然后将列表保存到数据库中。
我对HTTP只有一个基本的了解。我想要 POST 数组吗?我该怎么做?
这是一个 POST 示例,它向服务器发送一组水果。此代码将位于您的按钮点击功能内。
$scope.fruit = [{name: 'Apple'}, {name: 'Grape'}];
// Simple POST request example (passing data) :
$http.post('/someUrl', {fruit: $scope.fruit}).
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 的 angular 文档。这应该能帮到你。
我希望你选择 $resource,它包含在 ngResource
模块中。
在 post 调用中传递数组时,您需要在 $resource
选项
isArray
选项提到 true
代码
angular.module('app',[])
//factory will have resource object
.factory('myService',function($resource){
var postFruitData = function(){
return $resource('/savefruit', {}, {saveData: {method:'POST', isArray: true}});
}
return{
saveData: postFruitData
}
})
.controller('mainCtrl',function($scope,myService){
//this function needs to be call on post like form ng-submit
$scope.postFruitData = function(){
myService.saveData({}, $scope.data).$promise.then(function(data){
//you will get data here
});
}
});
有关更多信息,您还可以查看此 SO Question
希望对您有所帮助。谢谢。