【问题标题】:angular $http not sending any value into server角度 $http 没有向服务器发送任何值
【发布时间】: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


【解决方案1】:

我认为问题是由您将数据添加到 $http 调用的方式引起的。 你可以尝试改变你的控制器功能如下:

controller : function(){
  this.regdata = {};

  //Send Data
  this.addData = function(){
    var url = 'http://url.com/account/register';
    $http.post(url, this.regdata).then(function(dt){
      console.log(dt);
    },function(dt){
    console.log(dt);
    });
  };
}

您不必进行字符串化,因为 $http 服务会为您完成。

注意:该网址对我不起作用,因此我无法测试那部分代码。

【讨论】:

    【解决方案2】:
    $scope.myfun = function(id){
    
        data = "id="+id;
        $http.post("http://192.168.1.52/Angularjs/responce.php?get=true", data ,{headers : {'Content-Type': 'application/x-www-form-urlencoded'}})
            .success(function (response) {
    
            $scope.data1 = response;
    
            $scope.formid= $scope.data1[0].id;
            $scope.fName = $scope.data1[0].firstname;
            $scope.lName = $scope.data1[0].lastname;
    
            $scope.passw1 = $scope.data1[0].password;
            $scope.passw2 = $scope.data1[0].password;
    
    
            }
        );  };
    

    这对我有用

    【讨论】:

    • 它不是 JSON,我已经尝试过了。它已连接但未发送任何值
    • 对于发送值,您必须指定标头类型。在我的 codeigniter 项目中,当我通过标头类型发送时,我可以在我的控制器上接收值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多