【问题标题】:How to get a JavaScript array in the Python Pyramid framework?如何在 Python Pyramid 框架中获取 JavaScript 数组?
【发布时间】:2014-03-04 02:30:50
【问题描述】:

我正在尝试构建一个具有以下功能的网络应用程序:在某一时刻,用户将能够单击一个按钮以将一个“框”(带有 2 个输入字段)添加到他的页面。每个用户都可以添加多个“框”,因此 1 个用户的页面上可能有 2 个,另一个我有 5 个。我正在使用 jquery 来执行此操作,我的逻辑是这样的:

  • 用户点击“添加”按钮
  • html 元素作为字符串附加到空数组中
  • 我将此数组发送到数据库
  • 当用户返回时,我从数据库中检索数组并再次将其添加到 jquery 中

现在我已经成功完成了前 2 点(最简单 =D),但我被困在接下来的 2 点。

我正在为这个应用程序使用 Pyramid 框架,我认为应该有一种方法可以在 Pyramid 中获取该数组,以便我可以将它发送到数据库,但我无法弄清楚。

能否请您指点我一些文档,或者我可以从中学习如何做到这一点的其他东西?

HTML 代码:

<!DOCTYPE html>  
<html>  

<head>
    <link type= "text/css" rel="stylesheet" href="style.css"/>
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
    <script type="text/javascript" src='script.js'></script>
</head>

<body>
    <div class='add'></div>
    </div>
</body>

</html>

CSS 是这样的:

.add {
    border: 1px solid black;
    width: 30%;
    height: 40px;
    margin: auto;
    margin-top: 20%;
    position: relative;
}

.room {
    height: 150px;
    width: 40%;
    border: 1px solid black;
    margin: auto;
    margin-bottom: 1%;
    position:relative;
}

body{
    height: 100%;
    width: 100%;
}

以及 JQuery 代码:

var roomlist = new Array()

$(document).ready(function(){   
    $('.add').click(function(){
        roomlist.push('<div class="room"></div>')
        $('.add').before(roomlist[roomlist.length -1]);
        $('.add').css("margin-top","1%");
    });
});

【问题讨论】:

  • 博格丹,你绝对可以做到。但是,请显示您当前的 jQuery、html 和 python 代码。
  • @Raj 不幸的是,目前我没有任何 Python 代码,因为我还在学习 Pyramid。我的问题是(从我目前所读到的内容)我不知道我可以使用什么方法/技术从静态 js 文件中获取“房间列表”并将其作为变量添加到金字塔中。我的方法是考虑设计,找出我可能遇到的问题,学习修复它们的工具......编写实际代码
  • 这是您希望在 客户端 (在浏览器中为用户表示)发生的事情吗? jsfiddle.net/K2EzP
  • @Raj 是的,就是这样......现在我只是在考虑如何将数组存储在数据库中
  • 我在 Pyramid 文档中找到了一些关于 JSON 渲染器的内容......我会从那里检查并发布如果我能做到这一点

标签: javascript jquery python pyramid


【解决方案1】:

在 python 金字塔中,你会得到 json 渲染,你可以很容易地做到这一点。在金字塔中,您可以使用 GET、PUT、POST 和 DELETE 方法来获得宁静的 Web 服务。 通过使用 GET 方法,您可以在 jquery 中获取您的列表,并使用 POST 方法将您的列表保存在数据库中。

Ajax Development With JSON Renderers

GET、PUT 和 POST 方法示例

@view_defaults(route_name='myapi', renderer='json')
class GroupView(object):
   def __init__(self, request):
      self.request = request

   @view_config(request_method='GET')
   def get(self):
     # return information about the list or objest

   @view_config(request_method='PUT')
   def put(self):
      # update list or object

   @view_config(request_method='POST')
   def post(self):
      # Create new list or object

【讨论】:

    猜你喜欢
    • 2016-06-17
    • 1970-01-01
    • 2018-07-05
    • 2015-10-05
    • 2012-02-05
    • 1970-01-01
    • 2022-01-05
    • 2020-06-22
    • 2023-03-18
    相关资源
    最近更新 更多