简体   繁体   中英

How take data from json response in angularjs

hello everyone i have some issue in my controller i do http post to server and run of the server some file with php server side language and check if i the user is register in mydb this is my code:

 $scope.sendPost = function()
 {
    var login = 
        'mylogin='+ JSON.stringify({
            email: $scope.email,
            pass:  $scope.pass
        })

       $http({

          method : 'POST',
                    url : 'http://igortestk.netai.net/login.php',
                    data: login,
                   Content-Type:'text/plain', 
                    headers : {'Content-Type': 'application/x-www-form-urlencoded'}  
                  }).success(function(data){
                    console.log(data);



                    console.log(resultlogin);
                        console.log(json);



                    }).error(function(error){
                    console.log(error);
               })

from the sever side i back json_encode in php of some status of login so my question is how i take the json value from the server response this is my server response :

{"statuslogin":1}]

edit: this is my server side code in php;

$query="select * from `User` where Email='$email' and Pass='$pass'";

$result=mysql_query($query ,$con);
if(mysql_num_rows($result)==1){

    $reponse['statuslogin']=1;
}
else{
    $reponse['statuslogin']=0;
}

$output=json_encode($reponse);

print $output;

edit2:

ok it's doesnt work beacuse the data of the response is a string and data[0] i get "[" this bracket : data: "[{"statuslogin":1}]" so maybe some other solution ?

You can get the value with:

console.log(data.statuslogin);

In case of one array:

console.log(data[0].statuslogin);

$http({
    method: "POST",
    url: "http://igortestk.netai.net/login.php",
    data: login,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    }
}).success(function (data) {

    console.log(data[0].statuslogin); // In the console will print: 1

    // If you need to show a message according the result, you can do this:

    $scope.message = (data[0].statuslogin === 1) ? "Login success" : "Login error, please check";

}).error(function (error) {
    console.log(error);
});

However, according the AngularJS Documentation, the success method is deprecated:

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead.

https://docs.angularjs.org/api/ng/service/$http

Then, you might use the standard form with the shortcut form, by using then(). Something like this:

$http.post("http://igortestk.netai.net/login.php", data, { headers: { "Content-Type": "application/x-www-form-urlencoded" }}).then(function(response)
{
    console.log(response.data[0].statuslogin); // In the console will print: 1
}, function(response)
{
    console.log(response);
});

Demo

PHP File: loginajax.php

<?php
header("Access-Control-Allow-origin: *");
header("Content-Type: application/json");
header("Cache-Control: no-cache");

$reponse['statuslogin']=1;

$output=json_encode($reponse);

echo $output;
flush();
?>

 (function() { var app = angular.module("myApp", []); app.controller("Controller", ["$scope", "$http", function($scope, $http) { $scope.email = "email@server.com"; $scope.pass = "123456"; var login = 'mylogin=' + JSON.stringify({ email: $scope.email, pass: $scope.pass }); $http({ method: "POST", url: "http://dfjb.webcindario.com/loginajax.php", data: login, headers: { "Content-Type": "application/x-www-form-urlencoded" } }).success(function(data) { console.log(data.statuslogin); // In the console will print: 1 // If you need to show a message according the result, you can do this: //$scope.message = (data[0].statuslogin === 1) ? "Login success" : "Login error, please check"; }).error(function(error) { console.log(error); }); } ]); })(); 
 <html data-ng-app="myApp"> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> </head> <body data-ng-controller="Controller"> </body> </html> 

In the network tab of Google Chrome console, i have this json response:

在此处输入图片说明

The better way to access JSON data service is with ngResource which can be used to consume Restful API in AngularJs.

.factory('UserService', function ($resource) {
    return $resource('http://jsonplaceholder.typicode.com/users/:user',{user: "@user"});
});

To perform Resource get just do:

$scope.users = UserService.query();

resource object has the following methods:

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

To get a specific user:

$scope.oneUser = UserService.get({user: 1});

More info can be found here: https://docs.angularjs.org/api/ngResource/service/$resource

也许这对您有帮助

$http('http://igortestk.netai.net/login.php').post(data).then(function(data){ if(data.statuslogin === 1){alert('welcome');} });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM