简体   繁体   English

JSON输出的格式无效

[英]Format of JSON output not working

I have a problem with JSON format. 我有JSON格式的问题。 My goal is to generate a highcharts chart with data pulled from php via ajax. 我的目标是生成一个highcharts图表,其中的数据是通过ajax从php中提取的。 I finally got it all working except there is some problem with the format of the data output. 我终于完成了所有工作,除了数据输出的格式有问题。

So, in my data.php file I have: 所以,在我的data.php文件中,我有:

$result = array();
$result['name'] = '2013';
$x = mysqli_query($con,"
    SELECT Logdatetime, Temp
    FROM alldata 
    LIMIT 12"
);

while($r = mysqli_fetch_array($x)){
$result['data'][] = $r['Temp'];
}

print json_encode($result, JSON_NUMERIC_CHECK);

When I tried it, the output looked like this: 当我尝试它时,输出看起来像这样:

{"name":2013,"data":[-1.4,-1.4,-1.3,-1.3,-1.3,-1.3,-1.3,-1.2,-1.3,-1.2,-1.2,-1.2]}

Then in my main page I have the AJAX call like this: 然后在我的主页面中,我有这样的AJAX调用:

$.ajax({
    url : 'data.php',
    datatype : 'json',
    success : function (json) {
        alert(json);
        options.series[0].name = json['name'];
        options.series[0].data = json['data'];
        chart = new Highcharts.Chart(options);
    },
});
}

I put the alert there to check the data and the result is the same as the one above produced by PHP, so it seems correct. 我把警报放在那里检查数据,结果与PHP生成的结果相同,所以看起来是正确的。 However, there must be some problem with parsing the data contained in "data" and "name" - in other words, if I put: 但是,解析“data”和“name”中包含的数据肯定存在一些问题 - 换句话说,如果我放入:

options.series[0].name = json['name'];

nothing is inserted (alert produces "undefined"), if I put for example: 没有插入(警报产生“未定义”),如果我举例如:

options.series[0].name = json[1];

Then I get the name as the second character. 然后我得到名字作为第二个字符。 This means that there must be some problem with the interpretation of the JSON output by AJAX, but I wasnt able to figure out what the problem is. 这意味着AJAX对JSON输出的解释肯定存在一些问题,但我无法弄清问题是什么。

The jQuery $.ajax property is "dataType", not "datatype". jQuery $.ajax属性是“dataType”,而不是“datatype”。 If you don't set the data type properly, you get the raw string as the parameter to the callback. 如果未正确设置数据类型,则将原始字符串作为回调的参数。

$.ajax({
    url : 'data.php',
    dataType : 'json', // <--- note the capital "T"
    success : function (json) {
        alert(json);
        options.series[0].name = json['name'];
        options.series[0].data = json['data'];
        chart = new Highcharts.Chart(options);
    }, // <--- GET RID OF THIS COMMA
});

You need to put data into that second line as well... Try this: 您还需要将data放入第二行...试试这个:

options.series[0].name = json.name;
options.series[0].name = json.data[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM