【问题标题】:Ajax unable to parse JSON dataAjax 无法解析 JSON 数据
【发布时间】:2015-03-15 19:03:57
【问题描述】:

我知道有很多关于同一主题的问题,我已经阅读了所有这些问题,但它们对我的情况没有帮助。

我正在尝试解析从我的服务器端 PHP 脚本返回的一些 JSON 数据。我已经使用 JSONLint 来验证 PHP 输出是一个有效的 JSON 字符串。

我有以下 ajax 代码:

$(document).ready(function(){
        $('#update-stats-submit').on("click", function(){
            if (requestRunning) { // don't do anything if an AJAX request is pending
                return;
            }
            $.ajax({
                type: "GET",
                url: "calculate.php",
                data: "q="+$("#table-info").val(),
                dataType: "json",
                success: function(data){
                    $("#update-result").animate({ opacity: 100 });
                    $("#update-result").html(data.output_msg);
                    $("#update-result").delay(3000).animate({ opacity: 0 });
                    setTimeout(function() {
                        $("#update-result").empty();
                    }, 4000);
                    alert(data.avg + "\n" + data.var + "\n" + data.count + "\n" + data.est + "\n" + data.min + "\n" + data.max);
                },
                error: function(xhr, ajaxOptions, thrownError){
                    $("#update-result").html(xhr.responseText + "\n" + xhr.status + "\n" + thrownError);
                }
            })
            return false;
        });
    });

我还没有让这段代码成功执行。每次返回以下错误。

200 SyntaxError: Unexpected end of input

从 calculate.php 返回的示例 JSON 输出:

{
"output_msg":"Success!",
"avg":5.79916666667,
"var":4.63505345486,
"n":40,
"est":"1",
"min":"3",
"max":"4"
}

任何提示将不胜感激。

【问题讨论】:

  • 相当肯定不是重复的
  • 响应应该是什么?直接在浏览器中输入 url 会得到什么?
  • 哪一行导致错误?
  • "q="+$("#table-info").val(), 应该真的是 {q:$("#table-info").val()}, 以便正确编码。如果没有,您应该使用 encodeURIComponent()

标签: javascript jquery ajax json


【解决方案1】:

上面的ajax脚本基本上没有错。似乎该错误在于允许脚本在某些 GET 请求条件下退出()的服务器端 PHP 代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    相关资源
    最近更新 更多