0

我正在尝试使用 PHP 和 Google Charts 构建一些图表。我有一个 PHP 页面,其中包含一个表单,用户可以在其中选择他们希望在图表上看到的信息。表单包含日期范围、总销售额、净额等数据。表单提交给 GraphData.php。在这里,我想根据从表单提交中收到的数据生成 MySql 查询。我使用该数据为 Google Charts 构建 JSON 对象。然后将包含用户 ID 和会话变量的表单提交到 Graphs.php 页面。这里我们使用 Ajax 来获取 JSON 数据并创建 Google Chart。我在将重定向/表单提交到 Graphs.php 时遇到问题。这可能吗?这是我的 GraphData.php 代码:

// mysql stuff here ....
$result = mysql_query($sql, $myconn) or die(mysql_error());

//start the json data in the format Google Chart js/API expects to recieve it
$data = array('cols' => array(array('label' => 'Month', 'type' => 'string'),
                          array('label' => 'Ticket Sales', 'type' => 'number'),
                          array('label' => 'Amount Bet', 'type' => 'number'),
                          array('label' => 'Amount Won', 'type' => 'number'),
                          array('label' => 'Total Net', 'type' => 'number')),
          'rows' => array());

// loop through the results and add them to the json object
while($row = mysql_fetch_row($result)) 
{
    $data['rows'][] = array('c' => array(array('v' => $row[0]), array('v' => $row[1]), array('v' => $row[2]), array('v' => $row[3]), array('v' => $row[4])));
}

echo json_encode($data);
echo("<FORM id='redirect' name='redirect' method='POST' action='Graphs.php'>
        <INPUT type='hidden' name='userid' value='$userid'>
        <INPUT type='hidden' name='session' value='$session'>'
      </form>");
?>
<script type="text/javascript">
function submit () {
var frm = document.getElementById("redirect");
frm.submit();
}
window.onload = submit;
</script>

该页面成功重定向到 Graphs.php,但未提交表单,我收到一条错误消息,指出 JSON 字符串无效。我正在尝试做的事情真的可能吗?我只是做错了吗?还是有其他方法?对不起,如果这令人困惑。如果您想了解更多信息,请告诉我。任何帮助表示赞赏!提前致谢!!

4

1 回答 1

0

如果您有多个可能的值,您可以通过使用每个表单中的隐藏值来完全消除页面跳转,以使用 if/then 或 switch 语句来确定页面操作。作为伪:

if ($_POST[myHiddenInput]==null){
        (means the form hasn't been submitted)
        load or echo options form (form submits to this page)
}
else{
        (they submitted the filled out form)
        check the form for errors, re-populate and prompt if needed, etc.
        if no errors, query mysql (use PDO or face problems later),
         generate json from your sql response and use file_get_contents()
         or curl() google to get your chart, echo response to screen

}

您可以小心地将 php 嵌套在 javascript 中,允许您拥有一个 php 函数来创建您的 json 并将其返回给 javascript 函数调用(即:jquery ajax 请求),请记住,这只发生在页面加载时。

于 2012-11-05T22:03:23.177 回答