将数据类型作为 json 传递失败执行



我正在尝试通过JQuery/AJAX在页面加载时执行以下SQL查询。当我编写dataType: 'json',时,它不会发布,并且不会在控制台日志中提供错误。

我已经通过放置一个回显语句来测试SQL正在执行。没有线它回声,用线它不回声。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
//Load Questions
var getQuestions= true;
$.ajax({
type: "POST",
url: "comment.php",
context: document.body,
data:{getQuestions:getQuestions},
dataType: 'json', //<--This line here
success: function(data){
$("#updateDisplay").html(data);
}
});
});

SQL (注释.php(

<?php
//connect to db
include 'connect.php';
$getQuestions = $_POST['getQuestions'];;
if($getQuestions==TRUE){
$sqlQuery = "SELECT * 
FROM Questions 
ORDER BY QuestionID DESC";
$runQuery = mysql_query($sqlQuery) or die(mysql_error());
echo 'Test echo';
echo json_encode($runQuery);
}

在我有一个 DIV 放置结果之后:

<div id="updateDisplay">
//PHP loop will go here

我没有正确处理SQL输出以匹配JSON。

固定的 SQL

$runQueryArray=array();
$sqlQuery = "SELECT * 
FROM Questions 
ORDER BY QuestionID DESC";
$runQuery = mysql_query($sqlQuery) or die(mysql_error());
while (($row = mysql_fetch_array($runQuery, MYSQL_ASSOC)) !== false){
$runQueryArray[] = $row;
}
echo json_encode($runQueryArray);
}

还需要修复我的 JSON 调用:

$(document).ready(function() {
var getQuestions= true;
$.ajax({
type: "POST",
url: "comment.php",
context: document.body,
data:{getQuestions:getQuestions},
dataType: 'JSON',
success: function(JSON){
$.each(JSON,function(i,val){
$('#updateDisplay').append('<p>QuestionID: '+ val.QuestionID + ' Title: '+ val.Title+ ' Description: '+ val.Description+' Date Created: '+val.DateCreated+'</p><p><button type="submit" class="postReply" value='+val.QuestionID+'>Reply</button></p>');
});
}
});
});

最新更新