【问题标题】:Pyramid json view ajax call金字塔json查看ajax调用
【发布时间】:2014-07-02 16:51:37
【问题描述】:

我以前从未真正使用过 ajax,所以请你详细说明你的答案..

我有一个 Pyramid 应用程序,我想通过 ajax 加载信息,因为预加载它不可行。所以我想通过金字塔视图加载我需要的信息,但我不确定如何做到这一点。
我需要获取的信息在 MySQL 数据库中,所以我想我需要将鼠标单击事件对象 ajax_id 导入到 views.py 中才能进行查询。 (我可以毫无问题地获得ajax_id)

在我的views.py中我有:

@view_config(route_name="info_ajax",renderer="json")
def info_ajax(self):

    #for the sake of this example, lets just return the information from the mouse click event
    A = ajax_id      #is the id of the mouse click event
    B = ajax_name    #is the name of the mouse click event

    return {
                'a' : A,
                'b' : B,
        }

我通常会做的是预加载所有信息,但在这种情况下会花费很长时间,所以我不能只在views.py 中列出MySQL 查询,然后在我的.mak 文件中执行<script>window.coords = ${a|query_list};</script>

我想在我的 JavaScript 代码中将 ab 作为变量导入,这样我就可以再次使用它们,而无需在需要时重新加载它们。我该怎么做?

【问题讨论】:

  • 通常你会从一个使用 JSON 渲染器的视图返回一个字典或可以序列化为 JSON 的东西。渲染器本身转换为 JSON。对您来说很容易,也更容易在测试用例中进行测试。

标签: javascript python ajax json pyramid


【解决方案1】:

所以我想出了怎么做:

在金字塔view.py中:

@view_config(route_name="info_ajax",renderer="json")
def info_ajax(self):

    #for the sake of this example, lets just return the information from the mouse click event

    A = self.request.POST.get('ajax_id')    #is the id of the mouse click event
    B = self.request.POST.get('ajax_name')   #is the name of the mouse click event

    return {
                'ID' : A,
                'Name' : B,
        }

在 JS 中:

    $.ajax({
        type: "POST",
        url: "details",
        dataType: "json",
        data: {
            'ajax_id': iID,
            'ajax_name': sName,
        },
        success: function(data) {
                iReturned_value = data.ID;
            }, 
    })

【讨论】:

    【解决方案2】:

    已经有一个官方的金字塔教程提供了足够的背景来解决基本的 AJAX 任务。

    您需要更多教程吗?

    我最喜欢的高级教程是 ToDoPyramid(一个 Github 分支)

    【讨论】:

      猜你喜欢
      • 2014-08-03
      • 2014-07-16
      • 2020-07-29
      • 2017-10-19
      • 2015-12-19
      • 2013-11-11
      • 2015-05-20
      • 2014-04-20
      • 1970-01-01
      相关资源
      最近更新 更多