2014-06-26 15 views
0

我有這段代碼工作得很好,只是它會發布php的所有結果,我只想要特定的json_encoded數據。這是從我的數據庫中提取的PHP。如何從php/mysql發佈特定的json數據而不是所有數據

<?php 
session_start(); 
$_SESSION['charname'] = 'Egahtrac'; 

require_once ('mysqli_connect.php'); 

$q = "SELECT * FROM dps WHERE charname='" . $_SESSION['charname'] . "';"; 
$r = mysqli_query($dbc, $q); 
$row = mysqli_fetch_array($r, MYSQLI_ASSOC); 
$dmg = $row['dmg']; 
$curr_hp = $row['curr_hp']; 
$tot_hp = $row['tot_hp']; 
$attk_spd = $row['attk_spd']; 

if ($_SERVER['REQUEST_METHOD'] == 'POST') { 

    if (isset($_POST['attack'])) { 
     if ($curr_hp > 0) { 
      $row['curr_hp'] = $row['curr_hp'] - $row['dmg']; 

      $q = "UPDATE dps SET curr_hp='" . $row['curr_hp'] . "' WHERE charname='" . $_SESSION['charname'] . "';"; 
      $r = mysqli_query($dbc, $q); 

      echo json_encode($row); 
     } 
    } 
} 

這裏是jQuery的

$('input#attack').on('click', function() { 
    $.post('dpsloop2.php', { attack: true }, function(data) { $('span#curr_hp').text(data.dmg); }); 
}); 
// see here that i'm just trying to test if it works by echo'ing the dmg value to the curr_hp span to see if it changes. 
$('#dpsform').submit(function() { 
    return false; 
}); 

我知道這事做與的.text(數據)的一部分。但如果我試圖做.text(data.curr_hp)它不起作用。我已經檢查過,看到json數組正在迴應從php正確的格式,所以爲什麼我不能從JSON數組訪問data.curr_hp?

回答

0

在你的PHP中,你只應該調用echo json_encode(something)一次。 JSON響應必須是單個對象或數組;如果你想返回多個東西,你需要把它們放在一個數組中。所以,你應該只是做:

echo json_encode($curr_hp); 

然後需要使用dataType參數$.post()告訴它的響應是JSON。然後它會爲你解析它。

$.post('dpsloop2.php', {attack: true }, function(data) { 
    $('span#curr_hp').text(data); 
}, 'json'); 

如果你想要回整排,它應該是:

echo json_encode($row); 

和JS應該是這樣的:

$.post('dpsloop2.php', {attack: true }, function(data) { 
    $('span#curr_hp').text(data.curr_hp); 
    $('span#dmg').text(data.dmg); 
}, 'json'); 
+0

確定,所以說,我想拉從陣列中的所有數據到jQuery和我使用json_encode($行),這是數組,我可以用data.curr_hp只能訪問curr_hp數據? – Egahtrac

+0

是的,你可以這樣做。我打算展示該版本,但後來我看到評論說:「我希望它只回顯curr_hp」。 – Barmar

+0

事實上,如果你只是回聲一個數字或字符串,你甚至不需要JSON - 你真的只需要它的數組和對象。 – Barmar

0

剛拿到它的工作,這裏的解決方案,它完美的作品。我不得不將數據聲明爲序列化數組。

$('input#attack').on('click', function() { 
var data = $(this).serialize(); 
$.post('dpsloop2.php', { attack: true }, function(data) { $('span#curr_hp').text(data.dmg); },"json"); 
});