首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP JSON数据构建和表单提交在一个页面上重定向

问PHP JSON数据构建和表单提交在一个页面上重定向
EN

Stack Overflow用户
提问于 2012-11-06 01:13:50
回答 1查看 491关注 0票数 0

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

代码语言:javascript
复制
// 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字符串无效。我正在尝试做的事情真的可能吗?我是不是做错了?还是有别的办法?如果这让人困惑,我很抱歉。如果你想了解更多信息,请告诉我。如有任何帮助,我们不胜感激!提前感谢!!

EN

回答 1

Stack Overflow用户

发布于 2012-11-06 06:03:23

如果您有多个可能的值,您可以通过在每个表单中使用隐藏值来确定页面操作,从而完全消除页面跳转。作为伪:

代码语言:javascript
复制
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请求),但要记住,只有在页面加载时才会发生。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13237004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档