我去年才开始学习计算机科学,尽管阅读了有关该主题的教科书,但我一直在挣扎。我找不到任何有关将ajax表单数据发送到python,然后在字典中进行检查,然后将其解析为json对象的信息。只是对此感到困惑。我知道字典有键和值对,试图获得用户输入的键和值...
我尝试不处理KeyError代码(例如KeyError),或更改字典的键,但我真的不知道从哪里开始。第一个代码是python,第二个代码是javascript
<div class="modal-content">
<p>Enter new chatroom name</p>
<form id="form1">
<input id="chatroom" autocomplete="off" autofocus placeholder="Name" type="text">
<input type="submit" class="submit_button" value="Submit">
</form>
</div>
class chatrooms(dict):
# __init__ function
def __init__(self):
self = dict()
# Function to add key:value
def add(self, key, value):
self[key] = value
chats = chatrooms()
#user to add a new channel
@app.route("/add_chatroom", methods=["POST"])
def create_chatroom():
# get chatroom name
chatroom = request.form.get("chatroom")
# get user name from local storage
username = request.form.get("username") # isn't this a string
# if the chatroom does not yet exist
chats.add(username, chatroom)
return jsonify({"success": True, "chatroom": chats[username][chatroom]})
return jsonify({"success": False})
document.querySelector('#form1').onsubmit = function() {
const request = new XMLHttpRequest();
const chatroom = document.querySelector('#chatroom').value;
const username = localStorage.getItem('name');
request.open('POST', '/add_chatroom');
// Callback function for when request completes
request.onload = () => {
// Extract JSON data from request
const data = JSON.parse(request.responseText);
// Update the result div
if (data.success) {
const contents = `${data.chatroom}`
alert(contents);
}
else {
alert('There was an error.');
}
}
// add data to send to the server
const data = new FormData();
data.append('chatroom', chatroom)
data.append('username', username);
// Send request
request.send(data);
return false;
};
返回jsonify({“ success”:True,“ chatroom”:chats [用户名] [chatroom]}) TypeError:字符串索引必须为整数
我遇到类似这样的错误,但是我不确定如何为自定义键键入字典。
感谢您的帮助
答案 0 :(得分:0)
使用int
:
return jsonify({ "success": True, "chatroom": chats[int(username)][int(chatroom)] })