我有這段代碼工作得很好,只是它會發布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?
確定,所以說,我想拉從陣列中的所有數據到jQuery和我使用json_encode($行),這是數組,我可以用data.curr_hp只能訪問curr_hp數據? – Egahtrac
是的,你可以這樣做。我打算展示該版本,但後來我看到評論說:「我希望它只回顯curr_hp」。 – Barmar
事實上,如果你只是回聲一個數字或字符串,你甚至不需要JSON - 你真的只需要它的數組和對象。 – Barmar