JSON编码失败

JSON Encode Failure

本文关键字:失败 编码 JSON      更新时间:2023-09-26

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页面,在那里我可以把数组分解成单独的div,有id分配给他们。这是我尝试的

<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>

我哪里错了??

从你在评论中发布的内容来看,你拥有的是一个对象数组。不是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为您转义值,因此您不必担心注入攻击。