【发布时间】:2015-08-25 05:35:01
【问题描述】:
我正在尝试将 JSON 数据发送到服务器,并希望从服务器获取响应文本。
这是我的代码:
app.directive("registerSection",['$http',function($http){
return{
restrict : "E",
templateUrl : "view/register-section.html",
controller : function(){
this.regdata = {};
this.addData = function(){
// Send Data
$http({method:'POST',url:'http://url.com/account/register',data:JSON.stringify(this.regdata)}).then(function(dt){
alert(JSON.stringify(dt));
},function(dt){
alert(JSON.stringify(dt));
});
};
},
controllerAs : "reg"
};
}]);
这是html代码:
<form name="registerForm" ng-submit="registerForm.$valid && reg.addData()" novalidate>
<input type="text" name="name" ng-model="reg.regdata.name" placeholder="Your Name" required><br />
<input type="email" name="email" ng-model="reg.regdata.email" placeholder="Your Email" required><br />
<input type="password" name="password" ng-model="reg.regdata.password" placeholder="Your Password" required><br />
<p>{{reg.regdata}}</p>
<button type="submit">Register</button>
我已经看过 angular 文档,但服务器仍然没有从客户端获取任何值。 我在堆栈溢出中看到了同样的问题,但它仍然没有解决这个问题。
对不起,我的英语不好,谢谢。
【问题讨论】:
-
您已将
this.addData指定为发出请求的函数,但您在哪里调用该函数? -
您也可以发布您的 HTML 吗?
-
不要通过
JSON.stringify运行您的数据,Angular 已经为您做到了。一个简单的$http.post('http://url.com/account/register', this.regdata)就足够了 -
@Phil - 我已经尝试不使用
JSON.stringify,但使用/不使用没有什么不同 -
指令中的控制器无权访问范围。我建议将 $scope 注入控制器,然后将
this更改为 $scope。
标签: javascript json angularjs http