2017-03-31 6 views
1

JSON文字列を受け取り、canvasJSグラフに入力しようとしています。文字列を正しく変換する方法を理解しようとするのは苦労しています。私にエラー与えサーバーからJSONを解析して変換しようとしています

newDataPoints='[{"x":1483648595798,"y":62},{"x":1483648598843,"y":63},{"x":1483648601969,"y":64},{"x":1483648605088,"y":65},{"x":1483648779011,"y":0},{"x":1483648847224,"y":16}]'; 

:未定義ではありません

function loadGraph(serialNum){ 

    $.post("../Modules/LoadGraph_Mod/load_graph_mod.php", 
    { 
     submit: 'loadGraph', 

     serial:serialNum 


    }, 
    function(data,status){ 

newDataPoints=data; 

       }); 

      var chart = new CanvasJS.Chart("chartContainer", 
       { 
       interactivityEnabled: true, 
       zoomEnabled: true, 
          panEnabled: true, 
          backgroundColor:"#000", 


          axisX: { lineThickness: 1, 
       lineColor: "#333", 
       interval: 4 

       , 
       intervalType: "minutes",     
       valueFormatString: "h:mm", 
       labelFontColor: "#777" 
          }, 


          axisY: { tickColor:"#333", 
          gridColor: "#222", 
          lineThickness: 1, 
       lineColor: "#333", 
       valueFormatString: "" , 
       maximum: 100   }, 
          data: [{ 
           dataPoints : newDataPoints, 
        markerType: "none", 
           color: "#9c9a0c", 
           type: "area", 
           xValueType: "dateTime" 

          }] 
         }); 

      chart.render(); 

} 

私はそれをテストしたが、直接私のサーバーの応答を挿入しようとしました:ここで働いされていない私は、しようとしているものですオブジェクト。私はJSON.parseを実行しようとしましたが、認識できないトークン「<」というエラーが発生しました。

私はこのようなチャートに直接文字列を貼り付けるとき、それは動作します:

data: [{ 
          dataPoints : [{"x":1483648595798,"y":62},{"x":1483648598843,"y":63},{"x":1483648601969,"y":64},{"x":1483648605088,"y":65},{"x":1483648779011,"y":0},{"x":1483648847224,"y":16},{"x":1483648860414,"y":17},{"x":1483648862560,"y":18},{"x":1483648865650,"y":19},{"x":1483648868773,"y":20}], 
       markerType: "none", 
          color: "#9c9a0c", 
          type: "area", 
          xValueType: "dateTime" 

         }] 

だから私はそれがで正常に動作、私は戻って私のサーバから取得するJSON文字列を変換する方法を把握しようとしています私のチャート。私はどんな助けにも感謝しています。ありがとう。

+0

あなたが戻ってサーバーからデータを取得し、JSON 'しようとしているときに私が疑うだろうJSONの代わりにWebページを取得しています。 – powerc9000

+1

'$。post 'は非同期です。チャートを 'function(data、status){'関数の内部に移動します。 –

+0

[非同期呼び出しから応答を返すにはどうすればよいですか?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

答えて

1

サーバーからの単純な要求を作成し、JSONオブジェクトを返すようにしようとしている場合、私はどうしたら、次の

var http = require('http'); 
http.get(yourUrl, (res) => { 
    const statusCode = res.statusCode; 

    let error; 
    if (statusCode !== 200) { 
     error = new Error('Request Failed' + statusCode); 
    } 

    if (error) { 
     console.log(error.message); 
    } 

    let body = ''; 
    res.on('data', (chunk) => { 
     //individual pre-processing here 
     body += chunk; 
    }).on('end',() => { 
     let parsedBody = JSON.parse(body); 
     //Whatever you want to do with the object 
    }).on('error', (err) => { 
     console.log(err); 
    }); 
}); 
関連する問題