我试图通过JQuery / AJAX在页面加载上执行以下SQL查询。当我写dataType: 'json',
并且在控制台日志中没有提供错误时,它不会发布。
我已通过放置echo语句测试了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(comment.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
答案 0 :(得分:0)
我没有正确处理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>');
});
}
});
});