web2py:如何将 python 数组复制到 javascript 数组中

发布于 2024-12-06 03:14:08 字数 903 浏览 1 评论 0原文

我目前在让 javascript 和 python 在 web2py 中进行通信时遇到问题。

控制器:(

def testDB():
        a=[]
        a.append('a')
        a.append('b')
        a.append('c')
        return dict(m=a)

最终这将被替换为数据库行数组) 目前我正在尝试将 m 中的值分配给 javascript 中的数组。我尝试了几种方法:

var t="{{=m}}";

返回大约 43 个无意义的字符。然后我尝试:

var t= new Array(); var i=0;"{{q=0}}"
"{{i=len(message)}}"
i="{{=i}}";
for(q=0;q<i;q++,"{{q=q+1}}"){
t[q]="{{m[q]}}";
}

失败了,因为每次循环时 python q 变量都会重置,这是我问题的核心。 我还尝试使用 pop:

for(q=0;q<i;q++,"{{q=q+1}}"){
    alert("{{m.pop()}}");
    }

但数组在循环开始时不断重置,因此它不断显示相同的变量。 有没有更简单的方法来复制数组,或者停止 python 变量重置,或者甚至简单地将 javascript q 变量插入“{{m[q]}}”?

根据我的发现,问题来自于 python 作为服务器端,所以你不能将 javascript 值分配给它的变量,但我不确定这与它的循环部分有什么关系(如果我做同样的事情)在循环之外,这些值不会重置)。常见的解决方案似乎是使用 ajax 或 json,但我想尽可能避免这种情况。谢谢

I'm currently having an issue with getting javascript and python to communicate in web2py.

controller:

def testDB():
        a=[]
        a.append('a')
        a.append('b')
        a.append('c')
        return dict(m=a)

(Eventually this will be replaced with an array of DB rows)
Currently I'm trying to assign the values in m to an array in javascript. I've tried this a few ways:

var t="{{=m}}";

Returns about 43 meaningless characters. Then I tried:

var t= new Array(); var i=0;"{{q=0}}"
"{{i=len(message)}}"
i="{{=i}}";
for(q=0;q<i;q++,"{{q=q+1}}"){
t[q]="{{m[q]}}";
}

Which failed because the python q variable would reset every time the loop did, which is the heart of my problem.
I also tried using pop:

for(q=0;q<i;q++,"{{q=q+1}}"){
    alert("{{m.pop()}}");
    }

But the array keeps resetting again at the start of the loop, so it keeps showing the same variable.
Is there a simpler way to copy the arrays, or to stop the python variables resetting, or even simply to plug the javascript q variable into "{{m[q]}}" instead?

From what I've found, the problem comes from python being server side so you can't assign javascript values to it's variables, but I'm not sure what that has to do with the loop part of it (If I do the same outside a loop, the values do not reset). The common solution seems to be to use ajax or json, but I'd like to avoid that if possible. Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦中楼上月下 2024-12-13 03:14:08

在 web2py(或任何服务器端模板语言)中,您无法按照现有方式将服务器端 Python 代码与客户端 Javascript 代码混合在一起。当请求该页面时,将评估 web2py 视图中的 Python,并生成纯 HTML 页面(包含 Javascript 代码)并返回到浏览器。浏览器无法获取任何 Python 代码,也无法混合执行 Javascript 和 Python。

仅当您有 {{=some_value}} (注意等号)时,web2py 视图才会将文本/代码插入页面中。因此,像 {{m[q]}} 这样的东西没有效果。如果您想查看浏览器从 web2py 接收到的内容,请查看浏览器中的页面源代码 - 它会向您显示视图生成的 HTML/Javascript 的最终结果。

至于您的特定问题,您可以使用 response.json() 将 Python 列表转换为 JSON 对象。但是,如果您按原样将其包含在视图中,它将转义所有引号,因此您必须将其传递给 XML() helper 以避免转义。像这样的东西:

var t = {{=XML(response.json(m))}}

In web2py (or any server-side template language), you cannot mix server-side Python code with client-side Javascript code the way you have. When the page is requested, the Python in the web2py view is evaluated, and a pure HTML page (with Javascript code included) is generated and returned to the browser. The browser doesn't get any of the Python code and cannot execute a mix of Javascript and Python.

The web2py view only inserts text/code into the page when you have {{=some_value}} (note the equals sign). So, things like {{m[q]}} have no effect. If you want to see what the browser is receiving from web2py, look at the page source in the browser -- it will show you the end result of the HTML/Javascript generated by your view.

As for your particular question, you can use response.json() to convert your Python list to a JSON object. However, if you include that as is in the view, it will escape all the quotes, so you have to pass it to the XML() helper to avoid the escaping. Something like this:

var t = {{=XML(response.json(m))}}
独夜无伴 2024-12-13 03:14:08

使用 json 模块:

>>> import json
>>> s = json.dumps(range(5))
>>> print repr(s)
'[0, 1, 2, 3, 4]'
>>> print json.loads(s)
[0, 1, 2, 3, 4]
>>>

Use the json module:

>>> import json
>>> s = json.dumps(range(5))
>>> print repr(s)
'[0, 1, 2, 3, 4]'
>>> print json.loads(s)
[0, 1, 2, 3, 4]
>>>
傲娇萝莉攻 2024-12-13 03:14:08

安东尼的回答不适用于 web2py 2.9.12 或更高版本。

要将 python 变量值分配给 javascript 变量,首先将其在控制器中转换为 json,然后传递给视图
在视图中,使用 XML() 将其分配给 javascript 变量,以便它不会转义

控制器

from gluon.serializers import json

def index():
    array = [1, 2, 3, 4, 5]
    dictionary = dict(id=1, name='foo')
    return dict(array=json(array), dictionary=json(dictionary))

视图

<script>
    var js_array = {{=XML(array)}};
    var js_dictionary = {{=XML(dictionary)}};
</script>

其他解决方案是使用 ASSIGNJS 辅助

控制器

def index():
    array = [1, 2, 3, 4, 5]
    dictionary = dict(id=1, name='foo')
    return dict(array=array, dictionary=dictionary)

视图

<script>
    {{=ASSIGNJS(js_array = array)}}
    {{=ASSIGNJS(js_dictionary = dictionary)}}
</script>

Anthony's answer doesn't work on web2py 2.9.12 or above.

To assign python variable value to javascript varible, first convert it to json in controller and then pass to view
And in view, use XML() to assign it to javascript varible so that it is not escaped

Controller

from gluon.serializers import json

def index():
    array = [1, 2, 3, 4, 5]
    dictionary = dict(id=1, name='foo')
    return dict(array=json(array), dictionary=json(dictionary))

View

<script>
    var js_array = {{=XML(array)}};
    var js_dictionary = {{=XML(dictionary)}};
</script>

Other solution is use ASSIGNJS helper

Controller

def index():
    array = [1, 2, 3, 4, 5]
    dictionary = dict(id=1, name='foo')
    return dict(array=array, dictionary=dictionary)

View

<script>
    {{=ASSIGNJS(js_array = array)}}
    {{=ASSIGNJS(js_dictionary = dictionary)}}
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文