javascript - 通过 AJAX 从 javascript 传递到 Python 的变量 - 未找到
问题描述
我想要做的是通过 ajax 将值从我的 js 传递给 python(以便稍后我可以使用它来对我的数据库应用一些过滤)。
但是,每次我试图在 python 中获取它时,我都会收到以下错误:
TypeError:“NoneType”对象不可下标。
这是我的js代码:
$(document).ready(function(){
// code to read selected table row cell data (values).
$("#myTable").on('click','button.btn.btn-primary',function(){
// get the current row
var currentRow=$(this).closest("tr");
var col1 = currentRow.find("td:eq(0)").text(); // get current row 1st TD value
var ids = {
'user_id': col1
};
$.ajax({
url: '/',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(ids),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
alert(col1);
});
});
这是我的蟒蛇:
@app.route('/', methods=['GET', 'POST'])
@login_required
def index():
if request.method == "POST":
data = {}
data['id'] = request.json['user_id']
return jsonify(data)
return render_template('index.html', title='Homepage')
发布请求似乎工作正常。仅当我尝试获取 python 时才给出错误:
data['id'] = request.json['user_id']
关于如何去做的任何建议?
PS我不太擅长js。刚开始。将不胜感激任何帮助和指导。
解决方案
不要使用 JSON.stringify 将数据传递到 POST 请求中。在 AJAX 的 POST 请求中,您必须传递整个对象。在 python 的服务器端,您可以在代码中通过在对象键中使用的键检索数据user_id
$.ajax({
url: '/',
contentType: 'application/json',
dataType: 'json',
data: ids,
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
我希望这会奏效,祝你好运!!
推荐阅读
- android - 获取微调器的参考值
- arrays - 单循环排序的复杂性
- python - Pandas shift() 列向下,但用以前的值替换 NaN 条目?
- sql - 旋转计算雪花
- c# - 如何获取有关错误消息的更多信息:“抛出异常:System.Web.Mvc.dll 中的‘System.NullReferenceException’”
- javascript - Puppeteer 多次返回最近的对象
- python-3.x - 如何让 re.sub 在组占位符之间添加一个反斜杠
- firebase - 参数类型“我的用户?Function(User)' 不能分配给参数类型'MyUser Function(User?)'。Flutter Firebase 应用程序构建问题
- tensorflow - 使用自动编码器从视频帧中检测异常,LSTM 如何在这里提供帮助。我需要做一个更好的模型
- android - Mockk,如何模拟在私有函数中使用的 JSONObject 构造函数