【问题标题】:Uncaught SyntaxError: Unexpected number error when loading JSON data from Jinja2Uncaught SyntaxError:从 Jinja2 加载 JSON 数据时出现意外数字错误
【发布时间】:2017-08-17 07:24:54
【问题描述】:

我正在使用 Google 应用引擎制作网站。我想显示来自 Google SQL 数据库的表格。我使用 Jinja2 将 DB 数据从 .py 传递到 .html。

但是我有一个问题:

Uncaught SyntaxError: Unexpected number" (line 88 in .html)

第 88 行是$.get(function({{jsondata|safe}});完整代码如下:

<script type="text/javascript">
    var table;


    $(function(){
        $.get(function({{jsondata|safe}}){
            var jsonobj = JSON.parse({{jsondata|safe}});
            console.log(jsonobj);
            table = $('#userindex').dataTable({ 
                "sPaginationType": "bootstrap",
                "sDom": "t<'row'<'col-xs-6 col-left'i><'col-xs-6 col-right'p>>",
                "bStateSave": false
            });
            $.each(jsonobj, function(key,value){
                table.fnAddData(value[0],value[1],value[2],value[3], value[4],value[5],value[6],value[7]);
            });
        });
    });
</script>

按F12可以看到JSON数据:

[[1, "u1", 27, "M", "ad1", "01043343883", "A34B", 0], [2, "u2", 24, "M", "ad2", "01099248819", "A35B", 0], [3, "u3", 0, "M", "ad3", "01043724865", "A36B", 0], [4, "u4", 0, "M", "ad4", "01043734865", "A37B", 0], [5, "u5", 24, "M", "ad5", "15555215554", "A38B", 4]] 

这是我的 Python 代码:

cursor.execute("""select no, u_name, age, gender, U_adress, phone, car_num, penalty from User;""")

data=cursor.fetchall() 
array_list=[]
for row in data:
    temp = (row[0],str(row[1]),row[2],str(row[3]),str(row[4]),row[5],str(row[6]),row[7])
    array_list.append(temp) 

jsondata=json.dumps(array_list)
db.commit()
db.close()

template_values = { 'jsondata':jsondata }

template = JINJA_ENVIRONMENT.get_template('User.html')
self.response.write(template.render(template_values))

【问题讨论】:

  • function({{jsondata|safe}}) 是错误的,这不是您要打印数据的地方,而是参数列表所在的地方
  • 这是jQuery.get( url [, data ] [, success ] [, dataType ] ) 不是jQuery.get(success, ...)
  • 如果在页面加载后立即运行get,为什么要这样做?在这种情况下,只做服务器端不是更好吗?

标签: javascript jquery python web jinja2


【解决方案1】:

您正在混合使用 2 个不同的概念来加载数据、插值和 AJAX。使用其中一种,不要同时使用。

如果您不需要实时更新页面中的数据,只需使用插值即可。去掉 AJAX 调用,直接把 Python 中的数据放到生成的 Javascript 中的一个变量中:

$(function(){
    var jsonobj = {{jsondata|safe}};
    console.log(jsonobj);
    table = $('#userindex').dataTable({ 
        "sPaginationType": "bootstrap",
        "sDom": "t<'row'<'col-xs-6 col-left'i><'col-xs-6 col-right'p>>",
        "bStateSave": false
    });
    $.each(jsonobj, function(key,value){
        table.fnAddData(value[0],value[1],value[2],value[3], value[4],value[5],value[6],value[7]);
    });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2012-11-12
    • 2023-02-08
    • 1970-01-01
    相关资源
    最近更新 更多