Я только начал изучать информатику в прошлом году и изо всех сил пытался читать учебники по этому предмету.Я нигде не смог найти информацию об отправке данных формы ajax в python, проверке их в словаре и последующем анализе в объекте json.Просто так запутался по этому поводу.Я знаю, что в словаре есть пары «ключ-значение», пытающиеся получить ключи и значения пользовательского ввода ...
Я пытался адресовать коды KeyError, такие как KeyError none, или изменять ключи dicts, но я действительно неНе знаю, с чего начать.Первый код - 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;
};
return jsonify ({"success": True, "chatroom": chats [username] [chatroom]}) TypeError: stringиндексы должны быть целыми числами
Я получаю подобные ошибки, но я не уверен, как вводить пользовательские ключи для диктовок.
Спасибо за помощь