$ HTTP POST在Angular.js [英] $http post in Angular.js

查看:186
本文介绍了$ HTTP POST在Angular.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习Angular.js。如何在Angular.js重新编写如下code?

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?

推荐答案

在当前的功能,如果你正在分配 $ scope.persons $ HTTP 这是一个承诺对象 $ HTTP 返回一个承诺对象。

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

因此​​,而不是分配 scope.persons 至$ HTTP应该分配 $ scope.persons 成功的内 $ HTTP 如下所述:

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

}

这篇关于$ HTTP POST在Angular.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆