2014-01-29 35 views
0

我在寫jQuery ajax和php的郵件驗證控制器。如何在控制器中獲取json對象在ajax

我在php控制器驗證消息後,我試圖通過ajax得到它,並通過jquery在屏幕上打印。

我的Ajax代碼看起來像錯誤的認爲

....

success: function(data) { 
    var jsonObj = jQuery.parseJSON(data); 
     if (jsonObj.result) { 
       //succes message 

     } 
     else { 
      $.each([jsonObj.errors],function(key,value){ 
       console.log(jsonObj.errors); 
      }); 

     } 
    } 

的console.log顯示:

[Object] 
0: Object 
email: "Email validation error message" 
name: "Name validation error message" 
phone: "phone validation error message" 
__proto__: Object 
length: 1 

.......

如何獲得電子郵件的價值在屏幕上打印? 我想要做的事情如: 如果電子郵件錯誤不是空的顯示錯誤消息。

+0

從控制器返回數據爲JSON,例如:返回數據爲JSON –

回答

1

您應該更改您的代碼如下:

success: function(data) { 
    var jsonObj = jQuery.parseJSON(data); 
    if (jsonObj.result) { 
      //succes message 

    } 
    else { 
     $.each([jsonObj.errors],function(key,value){ 
      if (typeof jsonObj.errors[0].email !== 'undefined') { 
       console.log(jsonObj.errors[0].email); 
      } 
     }); 

    } 
} 
+0

謝謝我的朋友,這有幫助。 –

0

比方說你在控制器的陣列:

Array 
    (
     [message] => json object from controller 
     [data] => Array 
      (
       [name] => user25354i 
       [profile_views] => 234 
      ) 

    ) 
$array = array('message'=>"json object from controller", 
       'data'=>array('name'=>'user25354i','profile_views'=>'234')); 

回報$數組:echo json_encode($array);exit;

現在的jQuery它會被視爲默認的json對象,所以你可以簡單地訪問這個數組,如下所示:

success: function(response) { 
    alert(response.message); 
    alert(response.data.name); 
    so on... 
    } 

希望它能回答你的問題!

相關問題