JSON.parse:JSON数据的第1行第1列的意外字符(php)

时间:2017-02-20 10:03:41

标签: javascript php json

我无法访问json数据,因为它总是失败并给出错误 SyntaxError:JSON.parse:JSON数据的第1行第1列的意外字符 search.php输出json数据但scripts.js输出json.parse错误 的的script.js

// execute when the DOM is fully loaded
$(function() {

    console.log("1");

    $("#q").typeahead({
        autoselect: true,
        highlight: true,
        minLength: 1
    },
    {
        source: search,
        templates: {
            empty: "no places found yet",
            suggestion: _.template("<p><%- subname %></p>")
        }
    });

    // re-center map after place is selected from drop-down
    $("#q").on("typeahead:selected", function(eventObject, suggestion, name) {


   });


});
function search(query, cb)
{
    // get places matching query (asynchronously)
    var parameters = {
        sub: query
    };
    $.getJSON("search.php", parameters)
    .done(function(data, textStatus, jqXHR) {
        cb(data);
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
        console.log(errorThrown.toString());
    });
}

的search.php

<?php

    require(__DIR__ . "/../includes/config.php");
    $subjects = [];
    $sub = $_GET["sub"]."%";
    $sql = "SELECT * from subjects where subname LIKE '$sub'";
    echo $sql;
    if($rows = mysqli_query($con,$sql))
    {
        $row = mysqli_fetch_array($rows);
        while($row){
            $subjects[] = [

            'subcode' =>$row["subcode"],
            'subname' => $row["subname"],
            'reg' => $row["reg"],
            'courseid' =>$row["courseid"],
            'branchid'  => $row["branchid"],
            'yrsem' => $row["yrsem"]
            ];
            $row = mysqli_fetch_array($rows);
        }
    }
    // output places as JSON (pretty-printed for debugging convenience)
    header("Content-type: application/json");
    print(json_encode($subjects, JSON_PRETTY_PRINT));

?>

1 个答案:

答案 0 :(得分:1)

您的问题的解决方案是 JSON.stringify

您需要将数据输出转换为字符串,即

function validateJSON(str) {
    try {
       JSON.parse(str);
    } catch (e) {
     return false;
    }
  return true;
}

然后使用

验证您的数据
{{1}}

然后你就可以得到你的结果了。要进行验证,您可以通过以下函数传递数据: -

{{1}}