2013-02-08 54 views
0

目前,我不能從我的jquery ajax訪問返回數據。其實,我甚至不知道我是否發送任何數據?我只需要從JSON格式的數據發送到PHP,並獲得響應作爲一個數組。如何處理來自jQuery AJAX的PHP響應?

感謝您的幫助。

HTML/JS/jQuery的

<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
    <meta name="format-detection" content="telephone=no" /> 
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /> 
    <title>Hello World</title> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> 
    <script src="https://github.com/douglascrockford/JSON-js/blob/master/json2.js"></script> 

    <script type="text/javascript"> 
     $(document).ready(function(){ 
      $("form").submit(function() { 
       var uname = document.getElementById("username").value; 
       var pword = document.getElementById("password").value; 
       var postData = { 
        username: uname, 
        password: pword 
       }; 
       alert(uname); 

       $.ajax({ 
       url: "test.php", 
       type: "GET", 
       data: postData, 
       dataType: 'json', 
       contentType: 'json', 
       cache: false, 
       success: function (data) { 
         alert(data); 
        } 
       }); 
      }); 
     }); 
    </script> 
</head> 
<body> 
    <form action=""> 
     <input type='text' id="username" name="username" placeholder="Username" /> 
     <br /> 
     <input type='password' id="password" name="password" placeholder="password" /> 
     <br /> 
     <input type="submit" id="submit" value="Login" /> 
    </form> 
</body> 

PHP

echo json_encode(array(
    'username' => $_GET['username'], 
    'password' => $_GET['password'] 
)); 
+0

你在提醒中看到什麼?您可能需要在那裏使用'JSON.parse'來將JSON轉換爲可用內容。而且,您是否嘗試過使用Firebug之類的工具來查看您發送的內容並返回? –

+0

其實,現在我只是做了一些編輯,看到我得到一個迴應,但它返回[對象對象]。如何將數組從JSON轉換回JS?我使用JSON.parse? – copilot0910

+0

@ copilot0910:您可能需要調用'JSON.parse(data);' –

回答

1

您正在爲提交事件的處理程序,但你似乎忘了,以阻止返回false基本的提交過程。

一個帶有空行爲的表單會將數據發佈到同一頁面(您的初始PHP頁面),所以AJAX回調函數會發送,但是之後,您將以基本方式重新發布。

在函數的最後添加一個return false(緊接在您的AJAX調用之後),然後您的表單將不會被提交,AJAX將被髮送,您將看到響應。

如果您使用的是Firefox,請安裝Firebug並查看網絡選項卡以查看Ajax調用發送的請求並檢查您的JSON響應。

祝你好運。