【问题标题】:Send Python information to a JavaScript file将 Python 信息发送到 JavaScript 文件
【发布时间】:2015-08-29 08:54:28
【问题描述】:

我是 Python 和 JavaScript 的新手,并且(尝试)使用 cola.js。我的 HTML 表单将信息发送到 Python,Python 将其转换为字典数组。

Class_Name(ndb.Model):
    class_title = ndb.JsonProperty()
def post(self):
    classname = self.request.get('classname') #user inputs 1 classname
    prereq = self.request.get('prereq') #user inputs 1 prereq
    new_dictionary = {}
    new_dictionary [classname] = prereq
    new_class = Class_Name(class_title = new_dictionary) #stores as a dictionary
    new_class.put()

    Class_data = Class_Name.query().fetch() #gets all instances of Class_Name

   *** code that goes in b/w sends back to input form if want to add more classes, else, goes to below code

        output = []
        for a in Class_data:
            jsonprop = a.class_title
            extracted_output = json.dumps(jsonprop)
            output.append(extracted_output)
        template_vars= {'Class_data': output}
        template = jinja2_environment.get_template('template/post.html')
        self.response.write(template.render(template_vars))

到目前为止,这是我的基本代码。我想使用 cola.js 将我的信息转换为图表,基本上将每个类及其先决条件映射出来。但是,cola.js 格式是一个 JavaScript 文件,看起来像这样:

graph = {
  nodes: [
  {
    id: 'A'
  }, {
    id: 'B'
  }, {
    id: 'C'
  }
],

links: [
  {
    id: 1,
    source: 'A',
    target: 'B'
  }, {
    id: 2,
    source: 'B',
    target: 'C'
  }, {
    id: 3,
    source: 'C',
    target: 'A'
  }
]
};

有什么方法可以告诉 JavaScript 获取我的 Python 数组,然后像这样将信息输入到 JavaScript 文件中?

graph = {
  nodes: [
  {
    id: 'Class1' **will put actual class name
  }, {
    id: 'Class2'
  }
],

links: [
  {
    id: 1,
    source: 'Class1',
    target: 'prereq'
  }, {
    id: 2,
    source: 'Class2',
    target: 'prereq'
  }
]
};

这是将我的 Python 信息转换为 JavaScript 格式的粗略代码。

nodes_array = []
nodes_dict = {}
links_array = []
links_dict = {}
graph_array = []

#loops through every element
for a in Class_data:
    jsonprop = a.class_title
    extracted_output = json.loads(jsonprop)

for c_class, prereq in extracted_output.iteritems():
    # for the links dictionary  
    counter_link = 1
    # creates {'id':'class1'}
    nodes_dict['id'] = c_class
    #creates [ {'id':'class1'},  {'id':'class2'}]
    nodes_array.append(nodes_dictionary)
    # creates {'id': 'counter', 'source': 'class1', 'target': 'prereq'}
    links_dictionary[id] = counter_link
    counter_link++
    links_dictionary[source] = c_class
    links_dictionary[target] = prereq
    # creates [{'id': 'counter', 'source': 'class1', 'target': 'prereq'}]
    links_array.append(links_dictionary)
    #creating the format --> 'nodes': [  {id: class1}, {id:class2},  {id:class3} ]"
    #creating the format --> 'links': [  {id: 1, source :class2, target :class3} ]"
    graph[nodes] = nodes_array
    graph[links] = links_array

【问题讨论】:

  • 您可以通过编程方式生成 JavaScript 文件;但通常更好的解决方案是 JavaScript 将使用例如 jQuery.ajax() 获取数据
  • 你可能正在寻找这个stackoverflow.com/questions/7020135/…

标签: javascript python


【解决方案1】:

您的 Python 脚本可以使用 the json module 以 JavaScript 可以理解的格式将图形写入文件。

如果你在 Python 中这样做:

import json

graph = {
    'nodes': [ {'id': 'Class1'}, {'id': 'Class2'} ],
    'links': [
        { 'id': 1, 'source': 'Class1', 'target': 'prereq' },
        { 'id': 2, 'source': 'Class2', 'target': 'prereq' }
    ]
}

with open('graph.js', 'w') as out_file:
  out_file.write('var graph = %s;' % json.dumps(graph))

结果是一个名为 graph.js 的文件,其中包含:

var graph = {"links": [{"target": "prereq", "source": "Class1", "id": 1}, {"target": "prereq", "source": "Class2", "id": 2}], "nodes": [{"id": "Class1"}, {"id": "Class2"}]};

如果您在加载自己的 JavaScript 文件之前加载 graph.js,您可以参考变量 graph 来使用您的图表。

【讨论】:

  • 感谢之前的cmets!我会尝试这样做,看看是否遇到任何麻烦。
  • 如果您对我的回答感到满意,请接受吗?
  • 我更新了我的代码并想知道如何将我的字典格式化成这样 {id: 'class'} 而不是 {"id': "class"},这就是我的我从我的文件中获取。您对我的代码也有任何提示吗?谢谢
  • { id: 'class' } 和 { "id": "class" } 之间没有语义差异。 JavaScript 以完全相同的方式对待它们。就文件而言,这是 JSON 所需的语法。我不知道为什么双引号会打扰你,但如果他们这样做,你就不能使用这种简单的方法。您必须编写自己的 Python 代码以生成所需格式的输出。我怀疑这种努力是不值得的。你的代码对我来说看起来不错。如果您对此有具体问题,您可能应该发布另一个问题。我对这个问题的回答让您满意吗?
  • 我不知道任何 JavaScript,所以我认为 JavaScript 必须具有特定的语法才能使代码工作。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2012-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-04-05
  • 1970-01-01
  • 2013-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多