【问题标题】:Passing dataType as json failing to execute将dataType作为json传递失败执行
【发布时间】:2017-08-09 02:06:56
【问题描述】:

我正在尝试通过 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

【问题讨论】:

  • 您有任何控制台错误吗?
  • 啊,是的,我知道,之前不知道怎么看,谢谢。错误是:jquery.min.js:2 jQuery.Deferred 异常:未定义 getQuestions ReferenceError:未定义 getQuestions 只有当我添加上面我写“我试图添加”的部分时才会出现错误没有它没有错误如果我在 ajax 调用之前声明它我没有收到错误,因为 cmets 不支持格式化,所以在上面更新了错误
  • 现在您正在顺利解决问题。

标签: php jquery sql ajax


【解决方案1】:

我没有正确处理 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>');
            });
        }
    });
});

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    相关资源
    最近更新 更多