通过Post方法将数据保存为JSON格式

时间:2014-11-27 08:49:36

标签: javascript json angularjs

我正在使用AngularJS。我想将数据以JSON格式发布到localhost服务器,即http://localhost:8080/out.json

应如何为此方案实施post方法?或者post方法的任何其他工作示例都能够以json格式保存数据。

感谢。

这是我的代码:

var app = angular.module('myApp', []);

app.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

app.controller('FormCtrl', function ($scope, $http) {
    
    $scope.data = {
        firstname: "default"
    };
	$scope.submitForm=function($scope, $http) {
		$http.post('someurl', JSON.stringify(data)).
			success(function(data) {
						console.log(data);
			}).
			error(function(data) {
						console.log(data);
			});
		};
});
<html ng-app="myApp">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  <script src="controller.js"></script>
</head>

<body>
  <div ng-controller="FormCtrl">
    <form name="saveTemplateData" action="#">
		First name:    <input type="text" ng-model="data.firstname">   <br/><br/>
		<button type="submit" ng-Click='submitForm()'>Submit</button>
	</form>
  </div>
</body>
	
</html>

2 个答案:

答案 0 :(得分:1)

您不需要使用stringily函数。 我想你忘了在$scope.

之前加data

尝试使用此代码:

$scope.submitForm=function($scope, $http) {
    $http.post('someurl', $scope.data).
        success(function(data) {
                    console.log(data);
        }).
        error(function(data) {
                    console.log(data);
        });
    };

修改

哦,我没有看到,但是当你宣布像$scope, $http这样的函数时,你不需要再次指定submitForm。如果你这样做,你将需要名为$ scope的变量,它不在同一范围内,你也无法访问数据。

$scope.submitForm = function() {
    $http.post('someurl', $scope.data).
        success(function(data) {
                    console.log("success" + data);
        }).
        error(function(data) {
                    console.log("error" + data);
        });
    };

答案 1 :(得分:1)

添加我的评论作为答案:

听起来您正在发送到与您所在域不同的域名。通常,您不能这样做,除非该域名接受此类请求。