你好,我有一个ajax表单提交,我想返回json数据。由于某种原因,它不能正常工作。当data.error返回时,它应该给我消息Email is incorect。其他回复也一样。我做错了什么?我的php有json头,数据类型也是json。
$(function() {
$("form#login").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "log.php",
data: $('form#login').serialize(),
dataType:"json",
success: function(data){
if(data.error == "yes")
{
$("#msg").html('Email is incorect.')
}
else if (data.mandatory == "yes")
{
$("#msg").html('please complete email and pass')
}
else if (data.tip =='user')
{
alert('it works'+ data.id);
}
},
error: function(){
alert("failure");
}
});
});
});
我的php
<?php
header('Content-Type: application/json');
session_start();
include ('core/dbconfig.php');
$password=$_POST['password'];
$usernume=$_POST['email'];
$hash = hash('sha512', $password);
if ($password=='' or $usernume=='')
{
$arr[] = array('mandatory' => 'yes');
echo json_encode($arr);
}
else
{
$stmt = $dbh->prepare("SELECT * FROM Users where Email=:username and Password= :hashed");
$stmt->bindParam(':username', $usernume);
$stmt->bindParam(':hashed', $hash);
$stmt->execute();
if ($row = $stmt->fetch())
{
$_SESSION['id_user']=$row['ID_User'];
$arr[] = array(
'tip' => 'user',
'id' => '3'
);
echo json_encode($arr);
}
else
{
$arr[] = array('error' => 'yes',);
echo json_encode($arr);
}
}
?>
答案 0 :(得分:2)
将$arr[] =
的所有php实例转换为$arr =
答案 1 :(得分:0)
if(data.error != undefined) ///i think this is the right way
{
$("#msg").html('Email is incorect.')
}else if(data.length == 0){
alert("No users available");
}else {
/*
you will have to do an iteration here of your
"data" parent object through your child objects
*/
for(var x in data){
if (data[x].mandatory == "yes")
{
$("#msg").html('please complete email and pass')
}
else if (data[x].tip =='user')
{
alert('it works'+ data[x].id);
}
} //close for
} //close else