我使用星級評分系統來顯示SQL的評分數據。每個可以評分的項目都有唯一的識別變量$ id,而rating tabl中的每個評分都有唯一的識別符$ storyidr。我想這個腳本顯示:AJAX不分離JSON字符串
- 平均得分
- 次該項目已被評爲數量。
這些值是可退回的,但它們一起顯示在頁面上,我看不出如何分離它們。例如,對於平均評分爲4且評分爲200次的項目。當用戶點擊通過AJAX返回的數據看起來像:
- 對於 '響應1' 4 「200」
- 對於 'RESPONSE2' 4 「200」
我想能夠獨立他們看起來像:
- 對於 '響應1' 4
- 對於 'RESPONSE2' 200
html頁面
<div id="products" style="">
<div class="rateit" data-storyidr="<?php echo $id; ?>">
</div>
<div class="averagevote">
<div style="display:block;" id="response<?php echo $id; ?>"><?php echo $avgratep; ?></div><br>
<div style="display:block;" id="response2<?php echo $id; ?>">RaTeD <?php echo $rankcount; ?> TiMeS</div>
</div>
</div>
<?php endwhile; mysqli_close($connection); ?>
<script type ="text/javascript">
$('#currentslide .rateit').bind('rated reset', function (e) {
var ri = $(this);
var value = ri.rateit('value');
var storyidr = ri.data('storyidr');
ri.rateit('readonly', true);
$.ajax({
dataType : 'json',
url: 'rate.php',
data: {storyidr: storyidr, value: value},
type: 'POST',
success: function (data) {
$('#response'+storyidr).replaceWith('Avg rating ' + data.avg + '/5');
$('#response2'+storyidr).replaceWith('Rated ' + data.cnt + ' times');
},
error: function (jxhr, msg, err) {
$('#response').append('<li style="color:red">' + msg + '</li>');
}
});
});
</script>
PHP
<?PHP
$storyidr=$_POST['storyidr'];
$mysqli = mysqli_connect($dbhost,$dbusername,$dbpasswd,$database_name) or die ("Couldn't connect to server.");
if (mysqli_connect_errno($mysqli))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO ratings (storyidr, rank, entry_date) VALUES ('$_POST[storyidr]','$_POST[value]',now());";
$sql .= "SELECT AVG(rank) AS avrank, COUNT(rank) AS countrank FROM ratings WHERE storyidr = $storyidr";
if($mysqli->multi_query($sql))
{ $mysqli->next_result();
if ($result = $mysqli->store_result())
{
$data = mysqli_fetch_assoc($result);
$avrank = $data['avrank'];
$countrank = $data['countrank'];
$avrankr = round($avrank,2);
if(is_null($avrank)){$avrank ="null";}
echo json_encode(array('avg' => $avrankr, 'cnt' => $countrank));
}
}
?>
'$阿賈克斯({數據類型: 'JSON',...});' – barell
你JS網絡le,你已經參與了AJAX調用。就像其他選項一樣...... – barell
@lazel刪除括號並在代碼中添加代碼行並不合適。 –