【问题标题】:SyntaxError: illegal character ' Passing a 2D List to JavaScriptSyntaxError: 非法字符 ' 将 2D 列表传递给 JavaScript
【发布时间】:2014-03-23 13:07:58
【问题描述】:

我正在使用 App Engine、Python、Flask、JavaScript/jQuery。我收到此错误:

语法错误:非法字符'

这是我的看法:

@login_required
def update_test(test_id):
    test = Test.get_by_id(test_id)
    return render_template('update_test.html', test=test)

通过测试模板。 test_data 将包含一个二维列表。这是模型:

class Test(ndb.Model):
    """Test Models"""
    test_name = ndb.StringProperty(required=True)
    num_mc = ndb.IntegerProperty(required=True)
    num_or = ndb.IntegerProperty(required=True)
    num_students = ndb.IntegerProperty(required=True)
    correct_answers = ndb.IntegerProperty(repeated=True,indexed=False)
    pt_values = ndb.IntegerProperty(repeated=True,indexed=False)
    test_data = ndb.JsonProperty(repeated=True)
    added_by = ndb.UserProperty()
    timestamp = ndb.DateTimeProperty(auto_now_add=True)

最后,我需要访问 JavaScript 中的列表来构建 HandsonTable 网格:

 var num_mc = {{test.num_mc}};
    var num_or = {{test.num_or}};
    var total_questions = num_mc + num_or;
    var num_students = {{test.num_students}};
    console.log({{test.test_data}});
    var data = {{test.test_data}};

除 test_data 外,所有变量都可以轻松通过。请帮助我访问 JavaScript 中的 python 列表。

【问题讨论】:

  • 是您的 javascript 或 python 中的语法错误,您得到的错误应该提供比您提供的更多信息
  • SyntaxError: 非法字符 console.log([[u'Answers', u'', u'', u'& #39;, u. 错误在 javascript 中。它出现在 Firefox Firebug 中。
  • 所以查看 test_date 的 json 输出并检查它实际上是有效的 json。
  • 值得编辑答案并将其标记为已接受(在这些部分中被认为是可以接受的 :-))
  • 我可以在 2 天内接受答案。会这样做。谢谢。

标签: javascript jquery python google-app-engine flask


【解决方案1】:

想通了

在视图中,使用

new_data = json.dumps(test.test_data)
return render_template('update_test.html', test=test, data = new_data, bad_test = test.test_data)

然后在模板中添加|safe

console.log({{data|safe}});

现在我可以访问 javascript 中的 python 列表了。

【讨论】:

    猜你喜欢
    • 2021-05-31
    • 1970-01-01
    • 2016-06-01
    • 2015-05-24
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多