首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Angular.js中的$http post

Angular.js中的$http post
EN

Stack Overflow用户
提问于 2013-04-09 14:20:45
回答 1查看 97.6K关注 0票数 18

我刚刚开始学习Angular.js。如何在Angular.js中重写以下代码?

代码语言:javascript
复制
var postData = "<RequestInfo> "
            + "<Event>GetPersons</Event> "         
        + "</RequestInfo>";

    var req = new XMLHttpRequest();

    req.onreadystatechange = function () {
        if (req.readyState == 4 || req.readyState == "complete") {
            if (req.status == 200) {
                console.log(req.responseText);
            }
        }
    };

    try {
        req.open('POST', 'http://samedomain.com/GetPersons', false);
        req.send(postData);
    }
    catch (e) {
        console.log(e);
    }

这是我目前所掌握的-

代码语言:javascript
复制
function TestController($scope) {
      $scope.persons = $http({
            url: 'http://samedomain.com/GetPersons',
            method: "POST",
            data: postData,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function (data, status, headers, config) {
                $scope.data = data; // how do pass this to $scope.persons?
            }).error(function (data, status, headers, config) {
                $scope.status = status;
            });

}

html

代码语言:javascript
复制
<div ng-controller="TestController">    
    <li ng-repeat="person in persons">{{person.name}}</li>
</div>

我的方向对吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-09 14:59:22

在当前函数中,如果您将$scope.persons赋值给$http,这是一个promise对象,因为$http返回一个promise对象。

因此,不是将scope.persons赋值给$http,而是应该在$http的成功内部赋值$scope.persons,如下所述:

代码语言:javascript
复制
function TestController($scope, $http) {
      $http({
            url: 'http://samedomain.com/GetPersons',
            method: "POST",
            data: postData,
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function (data, status, headers, config) {
                $scope.persons = data; // assign  $scope.persons here as promise is resolved here 
            }).error(function (data, status, headers, config) {
                $scope.status = status;
            });

}
票数 41
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15894650

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档