2017-08-16 53 views
-3

回到我從PHP返回JSON編碼數據阿賈克斯成功的功能,這裏是代碼廣東話訪問JSON編碼數據從PHP

<?php 
if ($run) { 
    $response=array(); 
    $response['email']=$email; 
    $response['name']=$name; 
    echo json_encode($response); 
    exit();  
}  
?> 

我想通過AJAX成功函數來訪問這些數據,這就是我試圖

<script type="text/javascript"> 
$("#contact-form").submit(function(e){ 
    e.preventDefault();  
    if (check()) {  
     $.ajax({ 
      url: 'reguser.php', 
      async: true, 
      cache: false, 
      data: $('#contact-form').serialize(), 
      type:'post', 
      success: function (result) { 
       var json = result; 
       obj = JSON.parse(json); 
       alert(obj.email); 
      } 
     }); 
    } 
}); 
</script> 

如何檢索電子郵件和姓名,我在後端PHP呼應..

+2

什麼是錯誤?並請分享完整的ajax請求 – Naincy

+0

我無法訪問的數據,它顯示undefined – gANDALF

+0

**什麼**顯示'undefined'? 'obj'或'obj.email'?或'結果'?或'$'?或者是其他東西? – Quentin

回答

0

必須設置,返回的數據是JSON,這應該工作

$.ajax({ 
     url: 'reguser.php', 
     async: true, 
     cache: false, 
     data: $('#contact-form').serialize(), 
     type:'post', 
     dataType:'json', 
     success: function (result) {  
      alert(result.email); 
      } 
     }); 
0

不要在你的Ajax請求

$.ajax({ 
    url: 'reguser.php', 
    cache: false, 
    dataType: 'json', // added return type of request 
    data: $('#contact-form').serialize(), 
    type:'post', 
    success: function (result) { 
     alert(result.email); 
     } 
    }); 

這將致力於以下變化。