JSON.parse:JSON数据(php)第1行第1列的意外字符 [英] JSON.parse: unexpected character at line 1 column 1 of the JSON data (php)

查看:210
本文介绍了JSON.parse:JSON数据(php)第1行第1列的意外字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am unable to access json data as it always fails and gives error as SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data search.php outputs the json data but scripts.js outputs json.parse error 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));

?>

推荐答案

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

Solution for your problem is JSON.stringify

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

You need to convert your data output into string i.e.,

 var yourDataStr = JSON.stringify(yourdata) 

,然后使用

JSON.parse(yourDataStr)

然后您可以得到结果.要进行验证,您可以在以下函数中传递数据:-

Then you can get your result. To validate, you can pass your data in below function :-

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

这篇关于JSON.parse:JSON数据(php)第1行第1列的意外字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆