2014-01-27 2 views
0

PHP를 사용하여 JSON "텍스트"를 생성하고 자바 스크립트에 같은 파일에 포함하고 싶습니다. 자바에서 JSON을 텍스트로 처리하는 방법과 Object를 처리하는 방법을 이해하는 데 문제가 있다고 생각합니다.자바 스크립트에서 PHP JSON 변수

참고 : mysql을 mysqli로 곧 변경하려고합니다. 먼저이 기능을 먼저 사용하고 싶습니다.

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
    <title>Knox QA tickets status</title> 
</head> 
<body> 
    <script src="am/amcharts/amcharts.js" type="text/javascript"></script> 
    <script src="am/amcharts/serial.js" type="text/javascript"></script> 

<?php 
    //$subm = "8"; 
    // This is being loaded from a selection html script 
    $subm = $_POST["submoduleID"]; 
    if(!isset($_POST["submoduleID"])) 
    { 
    // set it to the default container if it's not set. 
    $subm = "8"; 
    } 

    // Connect to MySQL 
    $link = mysql_connect('localhost', 'root', 'secret'); 
    if (!$link) { 
     die('Could not connect: ' . mysql_error()); 
    } 

    // Select the data base 
    $db = mysql_select_db('xqa_status', $link); 
    if (!$db) { 
     die ('Error selecting database \'test\' : ' . mysql_error()); 
    } 

    // Fetch the data 
    $query = ("select date, tested, passed from test_status where xqa_id=" . $subm . " order by test_status_id limit 10"); 

    $result = mysql_query($query); 

    // Make a josn formatted output 
    $rows = array(); 
    while ($r = mysql_fetch_assoc($result)) { 
     $rows[] = $r; 
    } 
    $chartData_json = json_encode($rows); 
    print $chartData_json; 
    mysql_close($link); 
?> 


<!-- Custom Function 
    <script> 
    AmCharts.loadJSON = function(file) { 
     // create the request 
     if (window.XMLHttpRequest) { 
     // IE7+, Firefox, Chrome, Opera, Safari 
     var request = new XMLHttpRequest(); 
     } else { 
     // code for IE6, IE5 
     var request = new ActiveXObject('Microsoft.XMLHTTP'); 
     } 

     request.open('GET', file, false); 
     request.send(); 

     // parse adn return the output 
     return eval(request.responseText); 
    }; 
    </script> --> 


<!-- chart container --> 
<div id="chartdiv" style="width: 600px; height: 300px;"></div> 


<!-- the chart code --> 
    <script> 
    var chart; 
    var chartData1 = "<?php echo $chartData_json; ?>"; 
    var myObject = JSON.parse(chartData1, reviver); 
    // create chart 
    AmCharts.ready(function() { 

     // load the data 
     // SERIAL CHART 
     chart = new AmCharts.AmSerialChart(); 
     chart.pathToImages = "am/amcharts/images/"; 
     chart.dataProvider = myObject; 
     chart.categoryField = "date"; 
     chart.dataDateFormat = "YYYY-MM-DD"; 

     // GRAPHS 

     var graph1 = new AmCharts.AmGraph(); 
     graph1.type = "smoothedLine"; 
     graph1.title = "Tested"; 
     graph1.valueField = "tested"; 
     graph1.bullet = "round"; 
     graph1.bulletSize = 5; 
     graph1.bulletBorderColor = "#FFFFFF"; 
     graph1.bulletBorderThickness = 2; 
     graph1.lineThickness = 2; 
     graph1.lineAlpha = 0.5; 
     chart.addGraph(graph1); 

     var graph2 = new AmCharts.AmGraph(); 
     graph2.type = "smoothedLine"; 
     graph2.title = "Passed"; 
     graph2.valueField = "passed"; 
     graph2.bullet = "round"; 
     graph2.bulletSize = 5; 
     graph2.bulletBorderColor = "#FFFFFF"; 
     graph2.bulletBorderThickness = 2; 
     graph2.lineThickness = 2; 
     graph2.lineAlpha = 0.5; 
     chart.addGraph(graph2); 

     // CATEGORY AXIS 
     chart.categoryAxis.parseDates = true; 
     chart.categoryAxis.autoGridCount = false; 
     chart.categoryAxis.gridCout = chartData.length; 
     chart.categoryAxis.gridPosition = "start"; 
     chart.categoryAxis.labelRotation = 90; 

     // LEGEND 
     var legend = new AmCharts.AmLegend(); 
     chart.addLegend(legend); 

     // CURSOR 
     var chartCursor = new AmCharts.ChartCursor(); 
     chartCursor.cursorAlpha = 0; 
     chartCursor.cursorPosition = "mouse"; 
     chartCursor.categoryBalloonDateFormat = "YYYY-MM-DD"; 
     chart.addChartCursor(chartCursor); 

     // SCROLLBAR 
     var chartScrollbar = new AmCharts.ChartScrollbar(); 
     chart.addChartScrollbar(chartScrollbar); 

     // 3D 
     // chart.angle = 30; 
     // chart.depth3D = 15; 



     // WRITE 
     chart.write("chartdiv"); 



    }); 

    </script> 

</body> 
</html> 

json으로 출력의 샘플이있다 : 여기 내 스크립트의

당신은 자바 스크립트 변수로 PHP의 출력을 지정해야
[{"date":"2014-01-09","tested":"12","passed":"32"},{"date":"2014-01-10","tested":"12","passed":"34"},{"date":"2014-01-11","tested":"22","passed":"34"},{"date":"2014-01-12","tested":"22","passed":"34"},{"date":"2014-01-13","tested":"40","passed":"34"},{"date":"2014-01-14","tested":"40","passed":"34"},{"date":"2014-01-15","tested":"40","passed":"34"}] 
+1

매우 명확하지 않습니다. 정확한 문제는 무엇입니까? – meda

+0

자바 스크립트와 PHP를 하나의 파일에 섞어 놓은 것입니다. 내 – tenub

+1

감사합니다. 패트릭, 내 문제를 해결했는데 Javascript는 JSON을 객체로 인식하지 못했습니다. 이는 "큰 따옴표"안에 있기 때문입니다. – user3239109

답변

2

: 다음

<script> 
    var json_data=<?php 

... 

?>; 

    // Do stuff with json_data 
</script> 

json_data은 자바 스크립트에서 배열 또는 객체가 될 것입니다 (JSON은 문자열이 아닌 배열 리터럴로 파싱되므로 더 이상 JSON이 아닙니다). 이것이 가장 가능성이 높습니다. json_data[0].data과 같은 배열로 작업 할 수 있기 때문입니다.

+0

json 주위에 따옴표를 추가하는 것을 잊지 마십시오. 다음과 같이 작성하십시오 : var json_data = ""; – mat

+4

@mat, json은 자체적으로 따옴표를 포함하므로 오류가 발생합니다. javascript를로드하면' "{"somevar ": somevalue"} "'와 같은 sometihng가 표시되고 오류가 발생합니다. Paulpro가 가지고있는 방식으로 json 문자열은 객체 리터럴로 취급됩니다. –

+0

하지만 여기에 변수가 있습니다 : var chartData1 = ""; 큰 따옴표가 실제로 문제가되었습니다. – user3239109

관련 문제