我是一個python新手。我試圖用python來查詢數據庫。我需要傳遞一些參數到python頁面,以便它可以查詢數據庫。但是我無法檢索後期變量。從jquery中檢索python中的post變量
HTML:
<select class="chooseRace" id="race">
<option value="president">Presidential</option>
<option value="governor">Gubernatorial</option>
<option value="senate">Senatorial</option>
</select>
的jQuery:
var e = document.getElementById("race");
var strRace = e.options[e.selectedIndex].value;
$.ajax({
url: "http://localhost/py/getRaces.py",
method: "POST",
data: {level: strLevel},
success: function(data) {
// Successful POST; do something with the response if you want
console.log("ok, it worked. ");
},
error: function(jxhr, statusText, err) {
// Error, handle it
console.log(statusText + " " + err);
}
});
蟒蛇:
import MySQLdb
import cgitb
cgitb.enable()
import json
import requests
print "Content-Type: text/html" # HTML is following
print
print request.POST['level'] # for POST form method
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="user", # your username
passwd="pass", # your password
db="my_dbs") # name of the data base
cur = db.cursor()
cur.execute("SELECT * FROM mytable")
但是當我運行本地主機/ PY/getRaces.py,我得到這個:
<type 'exceptions.NameError'> Python 2.7.8: C:\Python27\python.exe
Tue Jul 22 14:58:21 2014
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
C:\code\getRaces.py in()
7 print "Content-Type: text/html" # HTML is following
8 print
=> 9 print request.POST['level'] # for POST form method
10
11 db = MySQLdb.connect(host="localhost", # your host, usually localhost
request undefined
<type 'exceptions.NameError'>: name 'request' is not defined
args = ("name 'request' is not defined",)
message = "name 'request' is not defined"
任何人都知道我在做什麼錯了?我以爲我安裝了請求庫。
我改變了行來打印requests.POST ['level'],錯誤信息是:'module'對象沒有屬性'POST' –
LauraNMS
編輯我的答案;沒有考慮到區分大小寫。 –
會導致錯誤::'function'object has no attribute'__getitem__' args =(「'function'object has no attribute'__getitem__'」,) message =「'function'object沒有屬性'__getitem__'「 –
LauraNMS