Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
816 views
in Technique[技术] by (71.8m points)

angularjs - $http post in Angular.js

I've just started learning Angular.js. How do I re-write the following code in Angular.js?

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);
    }

Here's what I have so far -

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

<div ng-controller="TestController">    
    <li ng-repeat="person in persons">{{person.name}}</li>
</div>

Am I in the right direction?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your current function if you are assigning $scope.persons to $http which is a promise object as $http returns a promise object.

So instead of assigning scope.persons to $http you should assign $scope.persons inside the success of $http as mentioned below:

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;
            });

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...