读取PHP返回的JS / JQuery中的JSON对象

时间:2016-11-06 19:52:01

标签: javascript php jquery json

所以,这是我的困境。我知道.js文件正在工作,它将json数据发送到PHP文件,PHP接收它并执行SQL命令。开发人员视图显示我正常运行。我的问题是在JS文件的'function(data){}'部分中,我不确定如何正确操作JSON数组,即我不知道如何检查json值是否返回=='success'。

非常感谢任何帮助或提示!

JS代码:

$(document).ready(function(){


$('#login_button').click(function(){
    //get values from input text boxes (Email & Password)
    var email = $('#email').val();
    var password = $('#password').val();

$.post('http://localhost:8888/php/login.php', {email1:email, password1:password}, function(data) {
    $("#login_button").html(result); //print JSON returned
    if (result[0] == "success"){ //check if 'success' returned by PHP file
        console.log(data);
        alert('working');
        window.location.replace("http://localhost:8888/index.html"); //
    } else {
        console.log(data);
        alert('error');
    }
    // console.log(data);
}, "json");

});//eo login_button
});//eof

PHP代码:

    <?php

//server info
$servername = "localhost";
$username = "root";
$dbpassword = "root";
$dbname = "personal_data";


//Establish server connection
$conn = new mysqli($servername, $username, $dbpassword, $dbname);


//Check connection for failure 
if (mysqli_connect_errno()) {
    $error = (mysqli_connect_error());
    echo "error";
    exit();
}


print_r($_POST);
//Read in email & password
$email = mysqli_real_escape_string($conn, $_POST['email1']);
$password = mysqli_real_escape_string($conn, $_POST['password1']); 

// echo $email;
// echo $password;

$sql = "SELECT Name, Age FROM personal_data WHERE Email='$email' AND Password='$password' LIMIT 1";
$result = mysqli_query($conn, $sql);

if(mysqli_num_rows($result) > 0){
        $jsonString = array('result' => 'success');
        echo json_encode($jsonString);
} else {
    $jsonString = array('result' => 'failure');
    echo json_encode($jsonString);
    }

mysqli_close($conn);
?>

1 个答案:

答案 0 :(得分:0)

成功功能中,您应该使用数据

$.post('http://localhost:8888/php/login.php', {email1:email, password1:password}, function(data) {
   $("#login_button").html(data); //print JSON returned
   if (data[0] == "success"){ //check if 'success' returned by PHP file
      console.log(data);
      alert('working');
      window.location.replace("http://localhost:8888/index.html"); //
   } else {
      console.log(data);
      alert('error');
   }
});