3

我正在尝试将整数的值从 javascript 函数中传递到服务器端 python 脚本。我试图找到一种方法将此值直接从 javascript 传递给 python,但尚未成功,因此我尝试使用 javascript 函数在我的 html 表单中创建一个包含我的 int 值的隐藏元素。然后在 Python Bottle 框架中使用“POST”操作,我尝试将值复制到我的 python 脚本中。但是,int 被处理为 NoneType,而不是 int,因此我不能在处理脚本中使用它。我的 JS 函数中使用 int 命名实例创建元素的部分如下

function newItem(){
  instance++;

  var oldInput = document.getElementById("itemInfo");
  var parent = oldInput.parentNode;
  var newDiv = document.createElement("div");

  var item = document.createElement("INPUT");
  var qty = document.createElement("INPUT");
  var color = document.createElement("INPUT");
  var count = document.createElement("HIDDEN");

  item.name = "item" + instance;
  qty.name = "qty" + instance;
  color.name = "color" + instance;
  count.value = instance;
  newDiv.appendChild(item);
  newDiv.appendChild(qty);
  newDiv.appendChild(color);
  newDiv.appendChild(count);

带有“POST”方法的 HTML 表单

<form method ="post" class="form" action = "/newguest" method = 'post'>
   Name: <input type="text" name="name"/>


   <p>Item: <input type="text" name="item"/> 
   Qty: <input type="text" name="qty"/>
   Color: <input type="text" name="color"/></p>
   <div class="itemInfo" id="itemInfo"></div>
    <input type ="button" value="Add Item" onclick="newItem();"/>


   <p>Phone: <input type="text" name="phone"/>
   Email: <input type="text" name="email"/>
   Artwork: <input type="file" name="file"/>
   <p>Quote: <input type="text" name="quote"/></p>
 </p>
   <p>Notes: <textarea cols="40" rows="10"></textarea>
 </p>
   <input type="submit" value='Add Order'/>
 </form>

最后是服务器端的python脚本

 @bottle.route('/newguest', method = 'POST')
def insert_newguest():
    name = bottle.request.forms.get("name")
    email = bottle.request.forms.get("email")
    item = bottle.request.forms.get("item")
    qty = bottle.request.forms.get("qty")
    color = bottle.request.forms.get("color")
    count = bottle.request.forms.get(count)
    itemDict = dict()
    qtyDict = dict()
    colorDict = dict()
    for num in range(1, count):

    itemkey = "item" + str(num)
    qtyKey = "qyt" + str(num)
    colorKey = "color" + str(num)
    itemDict[itemKey]= bottle.request.forms.get("item"+str(num))
    qtyDict[qtyKey] = bottle.request.forms.get("qty"+str(num))
    colorDict[colorKey] = bottle.request.forms.get("color"+str(num))

尝试使用“POST”方法添加信息时,我收到以下错误:

在此处输入图像描述

4

1 回答 1

1

您可能会收到此消息,因为您的隐藏字段尚未正确创建。

  • 首先,我看不到您newDiv在上面的代码中实际将 DOM 添加到 DOM 中。

  • 其次 - 您提供的 HTML 表单是硬编码的吗?如果是这样,那么为什么要对表单进行硬编码,然后在 javascript 中再次创建字段?这似乎有点奇怪。

  • 第三也是最重要的,因为隐藏字段只是一个<input>,你需要替换

    var count = document.createElement("HIDDEN");
    

    和:

    var count = document.createElement("INPUT");
    count.setAttribute('type', 'hidden');
    count.setAttribute('name', 'count');
    count.setAttribute('value', my_count_variable);
    

请参阅此答案和示例jsFiddle。现在,当您提交表单时,您的count字段应填充到 Python 脚本中。

顺便说一句,这种请求通常由 AJAX 处理。这个想法是相同的,只是您不需要刷新浏览器即可将您的计数发送到 Python 服务器。您可以在此处查看如何在没有 jQuery 的情况下执行此操作的示例。

于 2013-07-24T05:39:08.180 回答