我编写了一个 Python 脚本,用于将数据插入 PostgreSQL 数据库。我有一个带有几个按钮的简单 HTML 页面,但我很难将客户端上按钮单击的数据发布到服务器端的 Python CGI。
下面是 HTML、ajax 和 javascript 的样子:
''<div class="note" id="(Untitled)">
<script type="text/javascript" src="./jquery-2.1.1.js">
$(function () {
$('#1').on('click', function () {
$.ajax({
type: "POST",
url: "~/pythonscript.py",
datatype: "json",
data: JSON.stringify({
'param': {
"1"
}
}),
success: function (response) {
alert(response);
}
})
}
$('#2').on('click', function () {
$.ajax({
type: "POST",
url: "~/pythonscript.py",
datatype: "json",
data: JSON.stringify({
'param': {
"2"
}
}),
success: function (response) {
alert(response);
}
})
}
)
<body>
<a href="index2.html">
<button id="1">one</button><br>
<button id="2">two</button><br>
</a>
</body>
以下是一些 Python 的样子:
def cgi_get_from_ajax(self):
import json
import cgi
data = cgi.FieldStorage()
chosen = data.value
return chosen
def set_choice(self):
process = Name_of_class()
choice = process.cgi_get_from_ajax()
entry = []
if choice == '1':
entry = [1,0,0,0]
else:
entry = [0,0,0,1]
return entry
我做错了什么?
最佳答案
尝试将代码更改为:
data: {param: '2'} --- in the jQuery
data["param"].value ---- in the Python script
这通常对我有用。也许它也适合你;)
关于javascript - 在 HTML 中,如何使用 jquery 和 cgi 让 AJAX 将按钮点击发布到 .pay?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24333628/