2014-01-23 102 views
2

我創建了一個jquery ajax請求,並嘗試將一個變量傳遞給php來執行查詢並將數據返回給實際上下文。如何使用jquery ajax提供和獲取數據?

的實際情況下,處理Ajax:

 $.ajax({ 
     type: 'post', 
     url: 'show.php', 
     data: {name: name}, 
     dataType: 'json', 
     success: function(response) { 
     //here I'd like back the php query 
        } 

的PHP:

$hostelName = $_POST['name']; 

$sql = //here is the actual sql containing the $hostelname 

$query = mysql_query($sql); 

$obj = mysql_fetch_object($query); 
$sum = $obj->sum; 
$tour = $obj->tour; 


echo json_encode(
array(
    "sum" => $sum, 
    "tour" => $tour 
    ) 
); 
+1

你面臨的任何問題,而這樣做? –

+0

您的PHP代碼根本沒有錯誤檢查,例如,如果數據庫無法連接或查詢未返回任何行,則會導致各種問題。此外,mysql_ *函數已棄用,不應在新代碼中使用。使用mysqli或PDO代替 – GordonM

回答

3

如下解析試試這個:

$.ajax({ 
    type: 'post', 
    url: 'show.php', 
    data: "name="+ name, 
    dataType: 'json', 
    success: function(response) { 
    //here I'd like back the php query 
    } 

和你的PHP代碼到這一點:

$hostelName =mysql_escape_string($_POST['name']); 

    $sql = //here is the actual sql containing the $hostelname 

    $query = mysql_query($sql); 

    $reusult = mysql_fetch_assoc($query); 
    echo json_encode($reusult); 
+0

值得注意的是,在將用戶輸入('$ hostelName')注入'$ sql'之前需要將其轉義,否則OP將具有SQL注入漏洞。 – halfer

0

在你的PHP代碼,你正在返回響應爲JSON。所以只需要在代碼片段

$.ajax({ 
    type: 'post', 
    url: 'show.php', 
    data: {name: name}, 
    dataType: 'json', 
    success: function(response) { 
     //response is json you need to parse it 
     var json = response, 
     obj = JSON.parse(json); 
     alert(obj.sum); 
     alert(obj.tour); 

    }