angularjs $ http.post带参数 [英] angularjs $http.post with parameters

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

问题描述

我是棱角分明的新人,如果我的问题有点低,请不要生我的气。

I'm new at angular and if my question is kinda low lvl dont be angry with me.

我有网络服务,如果用户将通过身份验证,则返回sessionId和登录成功消息。例如url是:

I have web service which returns sessionId and login success message if user will pass auth. for example url is that:


http:// localhost:8181 / login?username = USERNAME& password = 12345

这是我的回复:

{"sessionId":"0997cec2a8b34c84ba8419ab1204e6aa","loginSucceeded":true}

这是我的登录控制器:

app.controller('loginCtrl', function($scope, loginService){
    $scope.login=function(user){
        loginService.login(user);
    }
});

这是我的服务:

app.factory('loginService', function($http){
    return{
        login: function(user){
            var $promise=$http.post('http://localhost:8181/login?', user);
            $promise.then(function(msg){
                if(msg.loginSucceeded=="true")
                    console.log("opa")
                else
                    console.log("den");
            });
        }
    }
});

我的范围内有user.username和user.password(使用文本框)。

and I have user.username and user.password in my scope (using textboxes).

如何在url中传递这些参数以及如何解析该响应?

How can I pass those parameters in url and how can I parse that response?

推荐答案

在您的代码中,您将在POST请求的URL中传递用户名和密码。如果这是你真正想要的(将它们作为POST数据传递更常见),你可以使用它:

In your code you're passing the username and password in the URL of the POST request. If that's what you really want (it's more common to pass them as POST data) than you can use this:

login: function(user){
    var url = 'http://localhost:8181/login?username=' + user.name + '&password=' + user.password;
    $http.post(url).then(function(msg){
        if(msg.loginSucceeded==="true"){
            console.log("opa")
        }else{
            console.log("den");
        }
    });    
}

如果要将数据作为POST数据传递,可以将其传递为 $ http.post()调用中的第二个参数:

If you want to pass the data as POST data, you can pass that as the second argument in the $http.post() call:

login: function(user){
    var url = 'http://localhost:8181/login';
    var data = {username: user.name, password: user.password};
    $http.post(url, data).then(function(msg){
        if(msg.loginSucceeded==="true"){
            console.log("opa")
        }else{
            console.log("den");
        }
    });
};

这篇关于angularjs $ http.post带参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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