dousu1900 2016-09-24 18:20
浏览 42
已采纳

我无法在角度js $ http.post中获得响应

I want to check whether the email id already exists in the db. If the email id exists, it should return false, else true. I'm not able to get the response. I've attached the controller code and the php code. [the variable validUser is undefined]

Controller.js

signUpApp.controller("signUpCtrl",function($scope,$http){
        $scope.register = function(form,user){
           if (form.$valid)
           {
             $http.post("http://localhost/checkUser.php?email="+user.email)
                  .then(function(response){
                      validUser=response;
                  });
             if(validUser=="true")
             {
               alert("valid user");
             }
             else
             {
               alert("already exists");
             }

           }
        }
     });

checkUser.php

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

$conn = new mysqli("localhost", "root", "", "user_details");
//$data = json_decode(file_get_contents("php://input"));
//$email = mysql_real_escape_string($data->email);
$email = $_POST['email'];
$result = $conn->query("SELECT count(*) as count from user where email='$email'");

$outp = "";
$rs = $result->fetch_array(MYSQLI_ASSOC)

    if ($rs['count']==0)
    {
        $outp ="true";
    }
    else
    {
        $outp ="false";
    }
$conn->close();

echo($outp);
?>
  • 写回答

2条回答 默认 最新

  • douwuying4709 2016-09-24 18:25
    关注

    You're not checking the response in the correct place, or rather - at the correct time.

    $http.post returns immediately. Your .then callback is called when the response is returned from the server. The code after the call to post (your if statements) is executed right after $http.post returns, and before the response is received from the server.

    You should place your validation code inside your callback:

    $http.post(...).then(function(response) {
        validUser = response;
        if(validUser==="true") { 
             ...
        } else if (validUser==="false") {
             ...
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog