简体   繁体   English

web2py:json序列化程序和javascript在python字符串周围存在引号问题

[英]web2py: json serializer and javascript has problems with quotes around python string

I want a complex 2d list to be brought from python to javascript. 我希望将复杂的2d列表从python带到javascript。 Javascript handles the numbers and list syntax (brackets and commas) just fine, but it can't understand the quotes around a string. Javascript可以很好地处理数字和列表语法(括号和逗号),但无法理解字符串周围的引号。 I have tried embedding the list directly to the code and converting it to json first, but neither works. 我尝试过将列表直接嵌入到代码中,然后先将其转换为json,但均无效。 I think problem is in that javascript somehow converts " to something else, I show what I mean in a minute. 我认为问题在于javascript以某种方式将"转换为其他内容,我在一分钟内就会明白我的意思。

But here's a sample code to reproduce the problem. 但是,这里有一个示例代码来重现该问题。

Action: 行动:

def problem():
    this_works = [[1,2,5,6.99],[24,55,6.8,124]]
    this_does_not = [["a",5,6,7],["b",8,9,10]]
    return dict(locals())

View: 视图:

{{extend 'layout.html'}}
{{from gluon.serializers import json}}

<p id="test_1">unchanged</p>
<p id="test_2">unchanged</p>
<p id="test_3">unchanged</p>

<script>
    var x;
    x = {{=this_works}};
    document.getElementById("test_1").innerHTML = x;

    var y;
    //y = {{=this_does_not}};
    document.getElementById("test_2").innerHTML = y;

    var z;
    //z = {{=json(this_does_not)}};
    document.getElementById("test_3").innerHTML = z;

</script>

If either of those two lines are uncommented, the code breaks. 如果这两行中的任何一条都未注释,则代码将中断。 If you check the source code of the html, you can see that web2py changes " to something else: 如果检查html的源代码,则可以看到web2py将"更改为其他内容:

<script>
    var x;
    x = [[1, 2, 5, 6.99], [24, 55, 6.8, 124]];
    document.getElementById("test_1").innerHTML = x;

    var y;
    //y = [[&#x27;a&#x27;, 5, 6, 7], [&#x27;b&#x27;, 8, 9, 10]];
    document.getElementById("test_2").innerHTML = y;

    var z;
    //z = [[&quot;a&quot;, 5, 6, 7], [&quot;b&quot;, 8, 9, 10]];
    document.getElementById("test_3").innerHTML = z;

</script>

For security reasons, the web2py template engine escapes all text inserted in the template. 出于安全原因,web2py模板引擎会转义插入模板中的所有文本。 To prevent this, you should use the XML() helper: 为了防止这种情况,您应该使用XML()帮助器:

y = {{=XML(this_does_not)}};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM