php ajax自动登录,无需表单操作

时间:2018-09-19 07:48:59

标签: php ajax

php ajax自动登录在表单操作中效果很好,但是没有表单操作也可以执行吗?

$email = 'xxx@gmail.com';
$password = 'password';

<script>
    var user = <?php $email; ?>;
    var pass = <?php $password; ?>;
    console.log(email=' + user + ', password=' + pass);
    $.ajax({
        url: 'http://www.example.com/login',
        type: 'POST',
        data: JSON.stringify({ email: user, password: pass }),
        success: function(data, status) {
            // do something after login
            console.log('success');
        },
        error: function() {
            console.log('error');
        }
    });

    return false;

    </script>

2 个答案:

答案 0 :(得分:0)

您应该改用GET方法。

$email = 'xxx@gmail.com';
$password = 'password';
<script>
var user = <?php $email; ?>;
var pass = <?php $password; ?>;
$.ajax({
    url: 'http://www.example.com/login',
    type: 'GET', //send it through get method
    data: { 
    email: user, 
    password: pass
    },
    success: function(response) {
    //Do Something
    },
    error: function(xhr) {
    //Do Something to handle error
    }
});
</script>

然后在登录页面中检查是否已通过GET或POST方法设置了电子邮件和密码参数。

<?php 

if (isset($_GET['email']) && isset($_GET['password']) || isset($_POST['email']) && isset($_POST['password'])){
// check your database and take actions.
}else{
// do nothing and show the post from again.
}

?>

答案 1 :(得分:0)

如果自动填写用户名和密码,以下代码可能会在页面加载时起作用。

希望对您有所帮助。

<script>

 $(document).ready(function(){

    var user = $('[name="username"]').val();
    var pass = $('[name="password"]').val();

    if(user !== '' && pass!== ''){

        $.ajax({
            url: 'http://www.YourUrl.com/login',
            type: 'POST',
            data: { 
                email: user, 
                password: pass
            },
            success: function(response) {
                   //When successfully logged in
            },
            error: function() {
                  //If error on server side script
            }
        });

      }

   });

在这里,我们创建了POST请求,您需要在$ _POST服务器端进行处理。