使用ajax响应中的变量作为json

时间:2016-05-07 07:21:15

标签: jquery mysql json ajax c3.js

我仍然是来自ajax和Jquery的新手,我将使用c3.js在图形中显示我的数据库,但我无法使用我的ajax响应javascript变量。这是来自response.php的JSON响应

[{"time":"2014-05-20 17:25:00","sensor1":"25","sensor2":"20","sensor3":"31","sensor4":"33","sensor5":"27"},{"time":"2014-05-20 17:26:00","sensor1":"26","sensor2":"23","sensor3":"33","sensor4":"31","sensor5":"23"}]

这是我的response.php

<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "perkebunan";

//Connect to MySQL Server
$server = mysql_connect($dbhost, $dbuser, $dbpass);

//Select Database
mysql_select_db($dbname, $server) or die(mysql_error());
//build query
$query = "SELECT * FROM sensor";    
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
$results = array();
while($row = mysql_fetch_assoc($qry_result))
{
    $temp = array(
        'time' => $row['time'],
        'sensor1' => $row['sensor1'],
        'sensor2' => $row['sensor2'],
        'sensor3' => $row['sensor3'],
        'sensor4' => $row['sensor4'],
        'sensor5' => $row['sensor5']
    );
    array_push($results,$temp);
}
echo json_encode($results);
?>

这是我的数据库

my database

所以请帮我在javascript中让我的json响应varible。这是我的试验index.php,使其成为可能。

<html>
<head>
    <!-- Load c3.css -->
    <link href="c3/c3.css" rel="stylesheet" type="text/css">
    <!-- Load d3.js and c3.js -->
    <script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <script src="c3/c3.js"></script>
    <script src="jquery-2.2.3.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
    <div id="chart"></div>
<script language="javascript" type="text/javascript">  
function graphAjax(){
    var response;
     $.ajax({
        type : 'POST',
        url : 'ajax-example.php',
        dataType : 'json',
        data: { },
        success: function(data){
            response=data;
        }
    });
    var chart = c3.generate({
    bindto: '#chart',
    data: {
        json: {response
            /* I hope this variable response give result like this
            time: [2014-05-20 17:25:00, 2014-05-20 17:26:00, 2014-05-20 17:27:00, 2014-05-20 17:28:00, 2014-05-20 17:29:00],
            sensor1: [25, 26, 27, 28, 29],
            sensor2: [20, 23, 22, 25, 28],
            sensor3: [31, 33, 35, 30, 33],
            sensor4: [33, 31, 28, 25, 27],
            sensor5: [27, 23, 21, 19, 18],
            */
        }
    }
    });
}
</script>

   <input type='button' onclick='graphAjax()' value='Start'/>
</body>
<footer>
</footer>
</html>
谢谢你的时间和帮助。

1 个答案:

答案 0 :(得分:0)

由于AJAX异步工作,你需要某种解决方法。例如,您可以在success回调函数中移动生成图表的函数(并定义在添加错误时会发生什么

success: function(data){
            response=data;
            // generate chart here
        },
 error: function () {
            // do something
        },

同时检查this extensive answerHow do I return the response from an asynchronous call?)或How to get the ajax response from success and assign it in a variable using jQuery?