2013-03-05 50 views
-2

PHP頁面:JSON編碼失敗

<?php 

include "linkpassword.inc"; 

function showVotes() 
{ 
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error()); 
$row = mysql_fetch_assoc($showresult); 
} 

function addVote() 
{ 
$sql= "UPDATE mms SET votes = votes+1 WHERE color = '".$_POST['color']."'"; 
$result= mysql_query($sql) or die(mysql_error()); 
return $result; 
} 


addVote(); 
showVotes(); 

?> 

我試圖讓陣列的輸出加載到一個JavaScript頁面,在這裏我可以打破了數組已分配給他們的ID單獨的div。這是我試過的

<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(showVotes[0]); 
      }, 
      error: function (jqXHR) { 
      } 
     }) 
    }) 
}); 
</script> 

我在哪裏出錯?

+3

你從來沒有初始化$結果,只有$迴應 – kennypu 2013-03-05 02:28:13

+2

你也似乎有兩次沒有理由的相同的查詢。 – lmortenson 2013-03-05 02:28:57

+4

如果你解釋了*出錯了,這將有所幫助。例如。你期望*會發生什麼,以及實際發生了什麼。目前,我們必須猜測。 – Hamish 2013-03-05 02:37:33

回答

1

從你在評論中發佈的內容,你有什麼是一個對象數組..不是HTML,因爲你的函數似乎表明。根據你想要做什麼,答案會是以下任,訪問該對象的屬性:

showVotes[0].votes 

或者

showVotes[0]['votes'] 

如:

$('#rvotes').html(showVotes[0].votes); 

或者等

第二次嘗試:

首先,當前的「showVotes」功能改成這樣:其次

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

,從頁面,以及通過任何其他(又名,其他產生的任何其他文字刪除您的「成功連接」文本函數返回結果指針)。我可能是錯的,但在我看來,其他文本的生成導致返回的json被解釋爲格式不正確。

上PDO快速的解釋:

try { 
    $dbh = new PDO("mysql:host=localhost;dbname=dbname", "user", "password"); 
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
} catch (\PDOException $e) { 
    echo "Error! Could not connect to database: " . $e->getMessage() . "<br/>"; 
    die(); 
} 

連接到數據庫。這是多麼我已經學會了這樣做,雖然我已經警告(和downvoted)不檢查錯誤這樣,儘管它從來沒有解釋過爲什麼。

數據庫交互:

$stmt = $dbh->prepare("UPDATE mms SET votes = votes+1 WHERE color = :color"); 
$stmt->bindParam(":color",$_POST['color']); 
$stmt->execute(); 

結果使用:

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
    $response[] = $row; 
} 

等等等等。 PDO爲你逃脫了價值,所以你不必擔心注入攻擊。

+1

@RobertMailloux:/對不起,我沒有更多的幫助。 – Daedalus 2013-03-05 03:02:50

+0

應該工作... [小提琴](http://jsfiddle.net/RVSNB/) – James 2013-03-05 03:12:12

+1

@RobertMailloux我不知道我理解你;可以你請澄清一下? – Daedalus 2013-03-05 03:17:49