我試圖從一個JavaScript函數內傳遞一個整數值到一個服務器端python腳本。我試圖找到一種方法來直接從javascript到python傳遞這個值,但尚未成功,所以相反,我試圖創建一個隱藏的元素,其中包含我的int值在我的HTML形式與JavaScript函數。然後在Python Bottle框架中使用動作'POST',我嘗試將值複製到我的python腳本中。但是,int正在作爲NoneType處理,而不是int,因此我無法在處理腳本中使用它。我的JS功能的它創建與INT命名實例元素的部分如下Javascript和Python之間傳遞變量
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」方法
<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腳本在服務器端的HTML表單
@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」的方法添加信息,我收到以下錯誤:
錯誤是「count」是在你的python的第8行賦值之前被引用的,你的意思是有'count = bottle.request.forms.get(「count」)'用引號括起count嗎? – carpeliam
對不起,是我的意思是把它周圍的報價,但後來我收到NoneType錯誤 例外: 類型錯誤(「範圍()整數結束參數預期,得到了NoneType」,) 回溯: 回溯(最近調用last): 文件「/usr/lib/python2.7/dist-packages/bottle.py」,行744,在_handle return route.call(** args) 文件「/ usr/lib/python2 0.7/DIST-包/瓶。文件「mainInventory.py」,第42行,在insert_newguest 中,範圍爲(1,count)的數字: TypeError:range()預期的整數結束參數,得到NoneType。 – sreisman