Ajax总是返回空值

时间:2017-10-24 02:56:17

标签: javascript php jquery ajax

我是PHP新手,现在我正在学习如何使用AJAX,我只想获得从PHP(webservice.php)传递给JS的返回值。我不知道为什么当我试图用我的JS登录功能上的“警报(结果)”提醒它时它总是返回空值。

我很抱歉我的英语不好,希望你们明白我的意思

HTML:

<input class="button btnlogin" type="button" class="alt" id="btn_submit_data" value="Log In" onclick="login()" />

JS:

function login() {
    var id = document.getElementById('login_email').value;
    var pass = document.getElementById('login_pass').value;
    $.get("http://localhost/project/dist/bin/webservice.php", {
        ajx: "login",
        email: id,
        password: pass
    }, function (result) {
        if (result == true) {
            window.location.href = "http://localhost/project/index.php";
        } else {
            alert(result);//This is where i want to get the value but it always returning the null value
        }
    });
}

PHP(connection.php):

<?php
    session_start();

    function getConnection(){
        $servername ="127.0.0.1";
        $username = "root";
        $password = "";
        $database = "project";
        $conn = new mysqli($servername, $username, $password,$database);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
        return $conn;
    }
    getconnection();
?>

PHP(webservice.php):

<?php
    include 'connection.php';

    if($_GET['ajx'] == "login"){
        $email = $_GET['email'];
        $password = $_GET['password'];
        Login($email,$password);
    }

    function Login($email,$password){
        return $email;
    }
?>

1 个答案:

答案 0 :(得分:0)

因为您的PHP代码没有返回任何内容。您在浏览器中获得的内容由PHP在输出缓冲区中返回的内容定义。 正如许多人所说,你应该使用:

$output = Login($email,$password);
echo json_encode($output);

您还应该包括:

header('Content-type:application/json;charset=utf-8');

另见this问题。