改进使用PHP获取数据库数据并将数据传递给JS

时间:2015-04-14 10:13:56

标签: javascript php json

我的目标是从数据库中读取数据并将其绘制在谷歌组合图表上,但我需要改进我希望将数据从PHP传递到控制组合图表的JS的方式

在PHP中,我已经能够连接到我的数据库,从中读取并从成功的读取查询中创建一个JSON数据数组。

我打算在我的主要PHP文件的最开始调用我的PHP代码,即

<?php include("../includes/db/dbread.php");?>

基本上我需要通过JS代码调用下面显示的成功运行的PHP代码,该代码将用于将JSON数组转换为适合在google组合图表中使用的形式

这是有效的PHP代码,即dbread.php:

    <?php
    // 1.Create a database connection
    define("DB_SERVER", "qwerty");
    define("DB_USER", "qwerty");
    define("DB_PASS", "qwerty");
    define("DB_NAME", "qwerty");

    $conn = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);

    // Test if connection occured
    if (mysqli_connect_errno()) {
        die("DB connection failed: ".mysqli_connect_error()."(".mysqli_connect_errno().")");
        echo "DB connection FAILED !!!!";
    } else {
        echo "DB connection worked !!!!";
    }
?>
<?php
    //function dummy_fetch_sets($dbtable) {

        $dbtable = "dummysets";

        // Perform DB query
        $query = "SELECT * FROM " . $dbtable;

        $result = mysqli_query($conn, $query);

        // Test for query error
        if ($result) {
            echo "DB connection worked !!!!";

            // Create array and set as 2nd element of response array
            $response["dummmysetsJSONArr"] = array();

            // Copy values populate array to be used to generate JSON data
            while($$dummysetsdetails = mysqli_fetch_assoc($result)) {

                $dummysetsJSONArr = array();

                $dummysetsJSONArr["entryID"] = $$dummysetsdetails["entryID"];
                $dummysetsJSONArr["distance"] = $$dummysetsdetails["distance"];
                $dummysetsJSONArr["calories"] = $$dummysetsdetails["calories"];

                // Push one or more elements onto the end of array
                array_push($response["dummmysetsJSONArr"], $dummysetsJSONArr);
            }

            // Set success value of response array
            $response["success"] = 1;

            //echo "Print out response in JSON format <br/><br/>"; 

            //echoing JSON response
            echo json_encode($response);
        } else {
            $response["success"] = 0;
            $response["message"] = "Could not SELECT ALL records";

            //echo "<br /><br />Print out response in JSON format <br/><br/>";     

            //echo JSON response
            echo json_encode($response);

            //echo "<br /><br />";

            die("DB " . $query . " query failed: " . mysqli_error($conn));
        }
    /*}

    function db_close() {
        if(isset($conn)) {
            // Close DB connection
            mysqli_close($conn);
        }
    }*/
?>

以下是来自此post的JS代码,我将使用它来获取上述PHP脚本中的JSON数据,即

// handles the click event for link 1, sends the query
function getSuccessOutput() {
  myLogger("getSuccessOutput called");

  getRequest(
      'http://www.demoonlyurl.com/test/json.php', // demo-only URL
       drawOutput,
       drawError
  );

  return false;
}

// handles the click event for link 2, sends the query
function getFailOutput() {
  getRequest(
      'invalid url will fail', // demo-only URL
       drawOutput,
       drawError
  );
  return false;
}

// handles drawing an error message
function drawError () {
    var container = document.getElementById('output');
    container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
    var container = document.getElementById('output');
    container.innerHTML = responseText;
}

function myLogger(content) {
    if (window.console && window.console.log) {
        console.log("mylogger - " + content);
    }
}

// helper function for cross-browser request object
function getRequest(url, success, error) {
    var req = false;

    try{
        // most browsers
        req = new XMLHttpRequest();

        myLogger(req);
    } catch (e){
        // IE
        try{
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            // try an older version
            try{
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                return false;
            }
        }
    }

    if (!req) { 
      myLogger("false");

      return false;
    }

    if (typeof success != 'function') {
      myLogger("if (typeof success != 'function') {");

      success = function () {};
    }

    if (typeof error!= 'function') {

      myLogger("if (typeof error!= 'function') {");

      error = function () {};
    }

    req.onreadystatechange = function(){

         myLogger("req.onreadystatechange = function(){");

        if(req .readyState == 4){

            myLogger("if (typeof error!= 'function') {");

            if(req.status === 200) {

              myLogger("req.status === 200");

              return success(req.responseText);
            } else {
              myLogger("req.status!= 200");

              return error(req.status);
            }

            //return req.status === 200 ? success(req.responseText) : error(req.status)
        }
    }

    req.open("GET", url, true);

    req.send(null);

     myLogger(req);

    return req;
}

以下是我打算将JSON数据数据传递给tutorials的我的Google组合图表代码。

    google.load("visualization", "1", {packages:["corechart"]});

google.setOnLoadCallback(drawVisualization);

function drawVisualization() {
  // Some raw data (not necessarily accurate)
  var data = google.visualization.arrayToDataTable([
    ['Month', 'Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6'],
    ['Set 1',  165,      938,         522,             998,           450,      614.6],
    ['Set 2',  135,      1120,        599,             1268,          288,      682],
    ['Set 3',  157,      1167,        587,             807,           397,      623],
    ['Set 4',  139,      1110,        615,             968,           215,      609.4],
    ['Set 5',  136,      691,         629,             1026,          366,      569.6]
  ]);

  var options = {
    title : 'Chart title',
    width: 1001,
    height: 500,
    vAxis: {
      title: "VAxis title"
    },

    hAxis: {
      title: "HAxis title"
    },

    seriesType: "bars",
    series: {5: {type: "line"}}
  };

  var chart = new google.visualization.ComboChart(document.getElementById('number_format_chart'));
  chart.draw(data, options);
}

这是我的qst:

我希望返回PHP代码的输出而不回显其结果,以避免打印但仍可供我的JS代码使用。

我该怎么做?

最新编辑:

正如AlfonsoJiménez所建议的那样,我整合了我的JS代码,使得函数drawVisualization()执行与返回JSON数据的PHP代码的交互。

我还没有使用JSON数组绘制条形图。我打算将我的JSON数据转换为2乘2的数组,以便能够将这些数据传递给

var data = google.visualization.arrayToDataTable([

如下面的代码所示,我无法打印我的JSON数组,即myLogger(“myLogger - JSON ARRAY - ”+ jsonarry);用于测试之前用它绘制图表

google.load("visualization", "1", {packages:["corechart"]});

google.setOnLoadCallback(drawVisualization);

function drawVisualization() {

  var req = false;
  var jsonarry;

  try {
      // most browsers
      req = new XMLHttpRequest();

      myLogger("myLogger - XMLHttpRequest() created");
  } catch (e){
      // IE
      try{
          req = new ActiveXObject("Msxml2.XMLHTTP");

          myLogger("myLogger - req = new ActiveXObject(Msxml2.XMLHTTP);");          
      } catch (e) {
          // try an older version
          try{
              req = new ActiveXObject("Microsoft.XMLHTTP");

              myLogger("myLogger - req = new ActiveXObject(Microsoft.XMLHTTP);");               
          } catch (e){
          }
      }
  }

  if (!req) { 
    myLogger("req === false");
  } else {

    myLogger("req === true");
  }

  req.onreadystatechange = function(){

       //myLogger("myLogger - req.onreadystatechange = function(){");

      if(req.readyState == 4) {

          myLogger("myLogger - req.readyState == 4");

          if(req.status === 200) {

            myLogger("myLogger - req.status === 200");

            jsonarry = req.responseText;

            myLogger("myLogger - JSON ARRAY - " + jsonarry);

            // Some raw data (not necessarily accurate)
            var data = google.visualization.arrayToDataTable([
              ['Month', 'Col1', 'Col2', 'Col3', 'Col4', 'Col5', 'Col6'],
              ['Set 1',  165,      938,         522,             998,           450,      614.6],
              ['Set 2',  135,      1120,        599,             1268,          288,      682],
              ['Set 3',  157,      1167,        587,             807,           397,      623],
              ['Set 4',  139,      1110,        615,             968,           215,      609.4],
              ['Set 5',  136,      691,         629,             1026,          366,      569.6]
            ]);

            var options = {
              title : 'Chart title',
              width: 1001,
              height: 500,
              vAxis: {
                title: "VAxis title"
              },

              hAxis: {
                title: "HAxis title"
              },

              seriesType: "bars",
              series: {5: {type: "line"}}
            };

            var chart = new google.visualization.ComboChart(document.getElementById('number_format_chart'));
            chart.draw(data, options);
          } else {
            myLogger("myLogger - req.status == " + req.status);
          }

          //return req.status === 200 ? success(req.responseText) : error(req.status)
      } else {
          myLogger("myLogger - req.readyState === " + req.readyState);
      }
  }

  req.open("GET", 'http://www.testingonetwo.com/dbread.php', true);

  req.send(null); 
}

function myLogger(content) {
    if (window.console && window.console.log) {
        console.log("myLogger - " + content);
    }
}

1 个答案:

答案 0 :(得分:0)

您现在使用的通讯方式是正确的。我看过你的截图(https://drive.google.com/file/d/0B2lBPXKQBuQHQngxS2g0ZEhUT2c/view?usp=sharing),这不应该发生。

阅读你的代码我无法看到你在哪里绘制图形,但我看到在drawOutput函数中你将你收到的内容添加到页面中(这可能就是它出现在顶部的原因)。尝试用这个替换这个功能:

function drawOutput(responseText) {
    drawVisualization(responseText)
}

您应该修改drawVisualization函数,以便它使用您传递的数据并将其附加到正确的html标记。