2013-03-05 71 views
0

*我知道MYSQL是depricated。我現在只是把它當作學習工具。來自SQL數據庫的AJAX PHP數組

修訂問題:

我更新了我的問題,使律更有意義......

如何顯示我的HTML頁面的輸出數組(在PHP文件的JSON數據),假設我想將它添加到div id rvotes?

的JavaScript

<script> 
$(document).ready(function() { 
$('.answer').click(function (e) { 
var color = $(this).attr("data-color"); 
$.ajax({ 
type: 'POST', 
url: 'mm.php', 
data: { color: color}, 
dataType: 'json', 
cache: false, 
success: function(showVotes) { 
$('#rvotes').html(row[0]); 
}, 
error: function (jqXHR) { 

} 

}) 
}) 
}); 
</script> 

PHP

function showVotes() 
{ 
$sql = "SELECT * FROM mms"; 
$result = mysql_query($sql) or die(mysql_error()); 
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error()); 
$response = array(); 
while($row = mysql_fetch_assoc($showresult)) 
$results[] = $row; 
echo json_encode($results); 
} 

ADDING我的HTML代碼

<div id="wrapper"> 

<div id="red" data-color="red" class="answer"> 
<a href="#"><img src="images/red.jpg" width="100%" /></a> 
</div> 

<div id="blue" data-color="blue" class="answer"> 
<a href="#"><img src="images/blue.jpg" width="100%" /></a> 
</div> 

<div id="green" data-color="green" class="answer"> 
<a href="#"><img src="images/green.jpg" width="100%" /></a> 
</div> 

<div id=rvotes> 
TEST 
</div> 

<div id=bvotes> 
TEST 
</div> 

我怎樣才能從陣列顯示輸出回到我的HTML頁面?

+0

那麼你的問題是什麼? – 2013-03-05 00:47:59

+1

MySql本身就很好。另外,我同意@JohnConde--你在問什麼? – 2013-03-05 00:50:01

+0

我編輯了文本。基本上,我試圖檢索PHP頁面上的PHP數組中的數據,並將其拉入HTML文檔。 – 2013-03-05 00:55:44

回答

3

我認爲這與此問題類似。

Get data from php array - AJAX - jQuery

,因爲它是在你的Ajax您無法訪問PHP數組。您需要先將它表示爲JSON,方法是將您的php數組傳遞給json_encode()函數並對其進行回顯。

echo json_encode($results); 

它將被傳遞給你的ajax回調參數。

在你成功Ajax回調,

success: function(showVotes) { 
$('#rvotes').html(showVotes[0]); 
}, 
+0

這不是比回答材料更多的評論材料嗎? – Pachonk 2013-03-05 01:02:35

+1

這是什麼,#rvotes?它是你的div嗎? – artsylar 2013-03-05 02:00:50

+1

但你是否能夠確認它是從PHP獲取正確的數據? – artsylar 2013-03-05 02:01:13

0

個人而言,我有我的PHP吐出預渲染HTML像這樣:

$sql = "SELECT * FROM mms"; 
$result = mysql_query($sql) or die(mysql_error()); 
    //I cleaned up redundant queries here... 
    //echo top border 
    echo "<table border='1'> 
    <tr> 
    <th>Color</th> 
    <th>Votes</th> 
    </tr>"; 
while($row = mysql_fetch_assoc($showresult)) 
while($row = mysql_fetch_assoc($showresult) 
    { 
    echo "<tr>"; 
    echo "<td>" . stripslashes($row['color']) . "</td>"; 
    echo "<td>" . stripslashes($row['votes']) . "</td>"; 
    echo "</tr>"; 
    } 

它吐出來的HTML後,只是這樣做:

<script> 
$(document).ready(function() { 
$('.answer').click(function (e) { 
var color = $(this).attr("data-color"); 
$.ajax({ 
type: 'POST', 
url: 'mm.php', 
data: { color: color}, 
success: function (showVotes) { 
$("#votes").html(showVotes); //this edits the text inside the div to be whatever your php spits out 
}, 
error: function (jqXHR) { 
} 

}) 
}) 
}); 
</script> 
<div id="votes></div>