2015-04-02 110 views
2

你好,我有一個Ajax表單提交,我想返回json數據。由於某種原因,它不適用。當data.error返回時,它應該給我的消息電子郵件是incorect。其他答案也一樣。我做錯了什麼?我的php有json頭,數據類型也是json。如何使用jQuery返回一個php 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

你得到什麼樣的回答? – 2015-04-02 15:23:35

+0

做一個'console.log(data);'並看看你的數據結構。這不是你所期望的(提示:'data'是一個**數組**)。請參閱[訪問/進程(嵌套)對象,數組或JSON](http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json)獲取更多幫助。 – 2015-04-02 15:23:52

回答

2

轉的$arr[] =所有你的php實例$arr =

+0

thnx,它的工作 – user3463807 2015-04-02 15:27:38

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 
相關問題