2012-06-07 133 views
-3

網址:http://localhost/test-mobile/log.php?username=&password=pass如何在ajax中獲取json響應?

$.ajax({ 
     url:url, 
     type:'POST', 
     data:{message:message}, 
     dataType:'json', 
     json:'members', 
     success:successData, 
     error:function(){ 
     alert("error") 
     } 
     }); 
     function successData(data){ 
    var response=data.message; 
    alert(response); 
} 

JSON響應低於{"members":{"httpCode":"400","message":"Username missing"}}

PHP代碼給出:

<?php 
    require_once("class/clsdatabase.php"); //Connect to SQL 

$username = $_GET['username']; 
$password = $_GET['password']; 

    //Check Username 
    if($username == '') { 
     $user = 'Username missing'; 
     $success = true; 
     $status = array("httpCode"=>"400", "message"=>$user); 
     //return $status; 
    } 

    //Check Password 
    if($password == '') { 
     $pass = 'Password missing'; 
     $success = true; 
    } 


    //Create SELECT query 
    $qry = "select * from user_register where emp_code='$username' AND emp_password='$password' AND active='1';"; 

    $result = mysql_query($qry); 
    $te = mysql_num_rows($result); 

    if($te == 0 && $username != '' && $password != '') { 
     $both = 'Invalid username or password'; 
     $success = true; 
    } 


    //If there are input validations, redirect back to the registration form 
    if($te != 0 && $username != '' && $password != '') { 

     $row = mysql_fetch_assoc($result); 
     $name = $row['emp_code']; 
     $success = true; 
     $status = array("httpCode"=>"400", "message"=>$name); 
     //return $status; 
    } 

//echo $_GET['callback']. '(' . json_encode($status) . ');';  
echo '{"members":'.json_encode($status).'}'; 

?> 

警報JSON響應

+0

請做一些代碼格式化。 –

+0

請以正確的格式輸入問題。現在沒人能猜到它是什麼了!!! – shobhit

+7

他只是一個新用戶,不需要downvote :( –

回答

3

我想起來分裂頁面分爲二。一個名爲ajax.php的文件和另一個名爲index.php的文件。

你的index.php看起來像這樣。

<html> 
<head> 
    <script type="text/javascript"> 

    postData={ajax:"testing",id:'123'}; 

    $.post('ajax.php', postData , function (data) { 
     alert(data); 
    }); 

    </script> 
</head> 
<body> 

</body> 
</html> 

而且你ajax.php文件看起來像

<?php 

// its important that this file only outputs json or javascript 
// content and nothing else. 

if(isset($_REQUEST['ajax'])){ 

    $ajaxRequest = $_REQUEST['ajax']; 

    if($ajaxRequest == 'testing'){ 

    // do some php stuff here -- if you look at the above example we sent an id variable 
    $sql = "SELECT FROM table WHERE id = {$_REQUEST['id']}"; 

    $results = query($sql); 

    echo json_encode($results); 
    exit; // exit the script here so that only the ajax stuff is output 

    } 

} 
+0

在一段時間內沒有完成PHP,但我認爲您可能需要json_decode($ _REQUEST) - 但是的,很好的建議。開始簡單 – Martin

+0

不,你不需要解碼它,因爲你沒有閱讀ajax.php頁面上的json數據,它只是一個正常的http請求,你正在輸出它。 –

0

jQuery的阿賈克斯功能自動解碼如果數據類型的JSON對象:「JSON」參數設置(這是他查詢)。所以傳遞給success()函數的'data'變量已經是一個JavaScript對象。

要訪問「消息」值,您可以使用「data.members.message」,因爲'members'對象包含'message'值。