首页 > 解决方案 > 将 pandas 数据框作为表格数组传递给 javascript

问题描述

这可能是一个非常简单的问题,但我对 javascript 完全陌生,无法弄清楚。

我正在努力创建一个散景图,它会在点击时更新 ColumnDataSource。在 javascript 回调中,我使用 ajax 调用,然后使用 php 从服务器获取更新的 pandasdf,到目前为止,大部分都运行良好。

尝试将 pandas 数据框作为 json 传递,我一直失败。我已经尝试了这里发布的几个答案,但它们都以某种方式将数组作为字符串传递。

这是问题的简化再现。

submit.html 提交表单,然后从 response.php 中获取一个数组

<!DOCTYPE html>
<link rel="shortcut icon" href="favicon.ico">
<html>
   <body>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">
$("document").ready(function(){
  $(".js-ajax-php-json").submit(function(){
    var data1 = {
      "action": "test"
    };
    data1 = $(this).serialize() + "&" + $.param(data1);
    $.ajax({
      type: "POST",
      dataType: "json",
      url: "response.php",
      data: data1,
      success: function(data) {
        console.table(data)
        $(".the-return").html(
        "return: " + data["index"]
        );

        alert("Form submitted successfully.\nReturned json: " + data["index"]);
      }
    });
    return false;
  });
});
</script>


    <form action="return.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
      <input type="text" name="st_numbers" value="" placeholder="write something" />
      </select>
      <input type="submit" name="submit" value="Submit form"  />
    </form>

    <div class="the-return">
      [HTML is replaced when successful.]
    </div>

</body>
</html>

响应.php

<?php
\\ a call to server-side python code to calculate and print( df.reset_index().to_dict('list'))
\\ $query = $_SERVER['QUERY_STRING'];
\\ exec($python." server_side_calc.py ".$query, $return)

\\ what it is doing is essentially the same as;
echo json_encode(["{'index': [0, 1, 2, 3], 'p': [10, 20, 30, 50], 'init': [0.5178, 0.11115, 0.1903, 0.026], '24': [0.385, 0.028, 0.104, -0.0052]}"]);
?>

这些程序将 pandas 数据帧读取为字符串"{'index': [0, 1, 2, 3], 'p': [10, 20, 30, 50], 'init': [0.5178, 0.11115, 0.1903, 0.026], '24': [0.385, 0.028, 0.104, -0.0052]}" 我不知道最外面的 blakets [] 去了哪里以及为什么它不能被识别为数组。

欢迎任何建议。

谢谢您的帮助。

标签: javascriptphppythonpandasbokeh

解决方案


推荐阅读