本文介绍了使用jquery调用json arrary的空白页面highchart的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php页面(array.php)。在浏览器中,array.php生成ff结果。

  [{name:London,data2:[ 70,19]},{name:Tokyo,data2:[60,18]}] 

array.php page

 <?php 
/ / header(Content-type:text / json);
header(Content-type:application / json);


$ db = mysql_connect(localhost,username,userpasswd);
mysql_select_db(weather,$ db);
$ query =SELECT * FROM measures;

$ result = mysql_query($ query,$ db);

while($ row = mysql_fetch_array($ result))
{
$ h = $ row [humidity];
$ w = $ row [windspeed];
$ t = $ row [temperature];
$ c = $ row [city];
$ ar1 [] = array(name=> $ c,data2=> [$ h,$ t]);
}
echo json_encode($ ar1);

?>

jquery页面的代码是

 <!DOCTYPE html PUBLIC -  // W3C // DTD XHTML 1.0 Transitional // ENhttp://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd> 
< html xmlns =http://www.w3.org/1999/xhtml>
< head>
< script src =https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js>< / script>
< script src =./ js / highcharts.js>< / script>

< script type =text / javascript>

var chart = null; //全局
$(文档).ready(函数(){
图表= new Highcharts.Chart({
图表:{
renderTo:'container',
defaultSeriesType:'column',
events:{
load:requestData
}
},
title:{
text:'来自实时数据数据库'
},
xAxis:{
categories:[]
},
yAxis:{
minPadding:0.2,
maxPadding: 0.2,
title:{
text:'Value',
margin:80
}
},
series:[]
} );
});
$ b $ **
*从服务器请求数据
* /
函数requestData(){

$ .ajax({
url:'array.php',
成功:函数(点){

$ .each(point,function(i,item){
var series_name = item.name;
var series_data = item.data2;

var series = {data:[]};

chart.xAxis.categories.push(series_name );
//chart.series.data.push (item.data2);
$ b $('body')。append(Name:+ series_name);
alert(series_data);

});


},
cache:false
});
}

< / script>

< / head>

< body>

< div id =containerstyle =min-width:400px; height:400px; margin:0 auto>< / div>
< / body>
< / html>

虽然代码并不完整。但直到错误被解决,我不能前进。如果我运行html代码,那么通过循环并提醒array.php中的每个数据,alert函数都能正常工作。但如果我取消注释

  // chart.xAxis.categories.push(series_name);或//chart.series.data.push (item.data2); 

则警报功能不再起作用。我有一种感觉,它不承认变量(图表)。我在
$ b $

  $(document).ready(function(){

使它成为一个全局变量,但它似乎并不如此。



你真的需要做一个Ajax调用吗?在php页面处理过程中你不能推送数据吗?我没有看到你做任何循环或实时更新图表,你只是试图加载数据加载,而不是Ajax,我会建议直接PHP。



至于你的问题,是图表没有实例化,当你是试图访问它我尝试重现您的问题@

一些更多的摆弄和调试让我想到这个解决方案

  function requestData(){
chart = this;
$ .ajax({
url:'array.php',
success:function(point){
$ .each(point,function(i,item){
var series_name = item.name;
var series_data = item.data2;
var series = {data:item.data2,name:series_name};
chart.addSeries(series) ;
});


},
cache:false
});
}

编辑
您的另一种选择方法可以像提及的@wergeld一样首先进行Ajax调用,然后在调用成功时创建图表,如下所示。 fiddle @

  var chart = null; 
$(function(){
requestData();
});

函数requestData(){
$ .ajax({
url:'array.php',
成功:函数(point){
var chartSeriesData = [];
$ .each(point,function(i,item){
var series_name = item.name;
var series_data = item.data2;
var series = {data:item.data2,name:series_name};
chartSeriesData.push(series);
});
chart = new Highcharts.Chart({
chart:{
renderTo:'container',
defaultSeriesType:'列',

},
标题:{
text:'来自数据库的实时数据'
},
xAxis:{
categories:[]
},
yAxis:{
minPadding:0.2,
maxPadding:0.2,
title:{
text:'Value',
margin:80
}
},
series:chartSeriesData
});
},
cache:false
});
}

}


I have a php page (array.php). On the browser, array.php produces the ff result

[{"name":"London","data2":["70","19"]},{"name":"Tokyo","data2":["60","18"]}]

array.php page

<?php
//header("Content-type: text/json");
header("Content-type: application/json");


$db = mysql_connect("localhost", "username", "userpasswd"); 
mysql_select_db("weather",$db);
$query = "SELECT * FROM measures";

$result = mysql_query($query,$db);

while($row = mysql_fetch_array($result))
{
$h = $row["humidity"];
$w = $row["windspeed"];
$t = $row["temperature"];
$c = $row["city"];
$ar1[] = array("name" =>$c,"data2"=>[$h,$t]);
}
echo json_encode($ar1);

?>

The code of the jquery page is

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="./js/highcharts.js"></script>

<script type="text/javascript">

var chart = null;      // global
$(document).ready(function() {
chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'column',
        events: {
            load: requestData
        }
    },
    title: {
        text: 'Real time data from database'
    },
    xAxis: {
            categories: []
        },
    yAxis: {
        minPadding: 0.2,
        maxPadding: 0.2,
        title: {
            text: 'Value',
            margin: 80
        }
    },
    series: []
});        
});

/**
 * Request data from the server
 */
function requestData() {

$.ajax({
    url: 'array.php',
    success: function(point) {

    $.each(point, function(i,item){
        var series_name = item.name;
        var series_data = item.data2;

        var series = {data: []};

        chart.xAxis.categories.push(series_name);
        //chart.series.data.push(item.data2);

        $('body').append( "Name: " + series_name);
        alert(series_data);

    });


    },
    cache: false
});
}

</script>

</head>

<body>

<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>

The code is not complete though. but until the error is fixed I can't move forward. If I run the html code, the alert function works well by looping through and alerting each of the data from the array.php. But if I uncomment

//chart.xAxis.categories.push(series_name); or //chart.series.data.push(item.data2);

then the alert function doesn't work any more. I have a feeling that it doesn't recognize the variable (chart). I have declared it before

$(document).ready(function() { 

so that it will be a global variable but it doesn't seem to be so.

Please, I truly need help. I being working on this for days now but no success. I will deeply appreciate it. Thanks in advance - Emma

解决方案

Do you really need to make an Ajax call? Can you not push the data during the page processing in php? I don't see you doing any loop or real time updates to the chart, you are just trying to load data at load, instead of Ajax, I would recommend direct php.

As far as your problem goes, yes chart is not instantiated at the time that you are trying to access it. I tried to reproduce your issue @ http://jsfiddle.net/jugal/Zjket/ Following are my findings

The requestData method is called during the call to Highchart's constructor. So? This means the constructor call isn't complete yet, and hence the object (chart) has not been instantiated yet. Highchart also supports having a callback method as a second param to its constructor, which it calls after construction (but still from the constructor, just that your chart is ready now, internally, but the constructor call has not yet returned to its caller) as chart = new Highcharts.Chart({...},requestData) but same problem persists. Strange? Not really, the requestData method gets called with the chart object as its context, this means that though you cannot refer to the "chart" using the chart variable, you can access it with this as the chart is the caller to requestData.

Unfortunately your problem just reaches the next level now, but the chart still wont show data, as now the new error being, your json is formatted incorrect [{"name":"London","data2":["70","19"]},{"name":"Tokyo","data2":["60","18"]}], the numbers shouldn't be inside quotes, it should instead be [{"name":"London","data2":[70,19]},{"name":"Tokyo","data2":[60,18]}] you will need to convert the values to numbers before you pass them to json_encode. Few more errors were encountered after fixing this. Also, you are not really supposed to push series to the chart.series object, instead use chart.addSeries(...) @ http://www.highcharts.com/stock/ref/#series

Some more fiddling around and debugging brought me to this solutionhttp://jsfiddle.net/jugal/JfgxX/

 function requestData() {
 chart=this;
 $.ajax({
url: 'array.php',
success: function(point) {
    $.each(point, function(i,item){
    var series_name = item.name;
    var series_data = item.data2;
    var series = {data: item.data2,name:series_name};
    chart.addSeries(series);
});


},
cache: false
});
  }

EDITAnother alternative to your approach can be, like @wergeld mentioned, to make the Ajax call first and then create the chart on success of that call, as follows. fiddle @ http://jsfiddle.net/jugal/j4ZYB/

 var chart=null;
$(function() {
   requestData();
});

function requestData() {
     $.ajax({
    url: 'array.php',
     success: function(point) {
      var chartSeriesData=[];
         $.each(point, function(i,item){
         var series_name = item.name;
         var series_data = item.data2;     
         var series = {data: item.data2,name:series_name};
        chartSeriesData.push(series);
        });
     chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'column'      ,      

    },
    title: {
        text: 'Real time data from database'
    },
    xAxis: {
            categories: []
        },
    yAxis: {
        minPadding: 0.2,
        maxPadding: 0.2,
        title: {
            text: 'Value',
            margin: 80
        }
    },
    series: chartSeriesData
});         
},
cache: false
});
  }

}

这篇关于使用jquery调用json arrary的空白页面highchart的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 09:36