PHP PAGE:
<?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>
我哪里错了?
答案 0 :(得分: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();
}
连接到数据库..这就是我学会这样做的方法,虽然我已经被警告(并且投票)不以这种方式检查错误,尽管从未解释过为什么。
数据库互动:
$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为您逃脱了价值,因此您不必担心注入攻击。