AJAX请求通过角度js POST到PHP脚本返回整个html页面不重定向

时间:2015-03-17 07:45:16

标签: php html ajax angularjs

JS

var app = angular.module('br', []);
app.controller('LoginCtrl', function($scope, $http) {
    $scope.valid = function() {
        var request = $http({
            method: "post",
            url: "php_files/login.php",
            data: {
                em: $scope.em,
                pw: $scope.pw
            },
        });

        request.success(function(data) {
            if (data == "invalid") {
                $scope.message = "Invalid email id or password!"
            }                
        });
    }
});

HTML

<body ng-controller="LoginCtrl">
    <form method="post">
        <table>
            <tr>
                <td>Email</td>
                <td><input type="email"  required="required" ng-model="em"/></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" required="required" ng-model="pw" /></td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit" value="Login" ng-click="valid()"/></td>
            </tr>
            <tr>
                <td colspan="2" align='center' style="color: red">{{message}}</td>
            </tr>
        </table>
    </form>
</body>

PHP脚本

include './include_db.php';
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$em = $request->em;
$pw = $request->pw;
$query = "select em,pw from users where em='$em' and pw='$pw'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$got_em = $row["em"];
$got_pw = $row["pw"];
if ($em != $got_em && $pw != $got_pw) {
    echo "invalid";
} else {
    session_start();
    $_SESSION["em"] = $em;
    header("Location:home.html");
}

现在我想要的是,如果电子邮件ID和密码错误,它应该返回无效的,但是如果它们是正确的,它应该重定向到无效的主页。

1 个答案:

答案 0 :(得分:0)

在php_files / login.php中:

if(!valid($username,$password)){
die("invalid");
} else {
die("https://logged_in_address");
}

在你的javascript中

                            request.success(function(data) {
                                if (data == "invalid") {
                                    $scope.message = "Invalid email id or password!"
                                } else {
                              window.location.replace(data);
/*redirect to the logged in page provided by login.php */
                               }
                            });