【问题标题】:Pass array back to Ajax with php and mysqli使用 php 和 mysqli 将数组传回 Ajax
【发布时间】:2014-06-27 19:57:40
【问题描述】:

我目前正在做一个小型项目,我有 2 个 mysql 数据库表(问题和答案)。答案表包含 questionid。我在 ajax 调用中使用以下查询选择一个问题和 4 个相关答案,它可以工作但不确定它是否正确?

然后我将其作为数组传回以显示在我的网页上。正在显示问题,但没有显示答案,但我可以在控制台窗口的回复中看到值在那里。我在想可能是因为问题和答案在同一个数组中?

非常感谢任何帮助。

php/mysqli

$sql= 'SELECT question FROM questions where difficulty = 1
UNION ALL
SELECT answer FROM answers a right join questions q on q.id = a.questionid WHERE q.difficulty = 1';
$result = $mysqli->query($sql) or die($mysqli->error.__LINE__);

if($result->num_rows > 0){
    $array = array(); // initialize
    while($row = $result->fetch_array(MYSQLI_BOTH)){
        $array[] = array(
        'question' => $row[0],
        'answer' => $row[1],
        'answer' => $row[2],
        'answer' => $row[3],
        'answer' => $row[4]
        );  
    }

}
header('Content-Type: application/json',true);
echo json_encode($array);   
$result->free();
$mysqli->close();

Ajax 成功响应

function response(json){
  console.log(json);
  var quest = json[0].question;
  var ans1 = json[1].question;
  var ans2 = json[2].question;
  var ans3 = json[3].question;
  var ans4 = json[4].question;
  $("#questionBox").html('<h2>Q: ' + quest);
  $("#answerBox").html('<h2>Q: ' + ans1);
}

Ajax 响应:

[{"question":"Is this an easy question?","answer":null},
{"question":"Yes","answer":null},
{"question":"No","answer":null},
{"question":"Maybe","answer":null},
{"question":"Who Knows","answer":null}]

直接从浏览器响应:

[{"question":"Is this an easy question?","answer":null},
{"question":"Yes","answer":null},
{"question":"No","answer":null},
{"question":"Maybe","answer":null},
{"question":"Who Knows","answer":null}]

【问题讨论】:

    标签: php jquery ajax mysqli


    【解决方案1】:
    var ans1 = json[1].question;
    

    不应该是这样的:

    var ans1 = json[0].answer;
    

    此外,您用于创建数组的 PHP 代码也具有相同的 answer 键 4 次,我想这意味着即使您设置了 4 个答案,您也只能在响应中得到 1 个答案。您可能希望将其更改为:

      $array[] = array(
            'question' => $row[0],
            'answer1' => $row[1],
            'answer2' => $row[2],
            'answer3' => $row[3],
            'answer4' => $row[4]
            ); 
    

    然后在javascript中:

    var ans1 = json[0].answer1;
    var ans2 = json[0].answer2;
    

    等等

    【讨论】:

    • 嗨,cole2,我试过了,但页面上仍然没有显示任何内容...?
    • 编辑了主要评论以显示响应中返回的内容
    • @Paul'Macca'McGill:谢谢。我看到你所有的答案都是null,所以你的 php 代码中有错误。你确定 $row[0] - $row[4] 是正确的吗?
    • 出于某种原因,实际的正确答案会针对“问题”显示?但是,如果将数组行全部更改为 'question' 并将变量更改为 .question;,那么所有内容都将变为 null 吗?
    • 还有其他人有什么想法吗?谢谢
    猜你喜欢
    • 2016-04-22
    • 2015-05-14
    • 2011-11-07
    • 2014-01-09
    • 2021-02-10
    • 1970-01-01
    • 2019-03-24
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多