Tengo un editor de código en vivo y no puedo eliminar el primer carácter, si selecciono todo el texto y presiono delete o backspace , no hace nada.
¿Que puedo hacer?
HTML:
<!doctype html> <html> <head> <title>Live Code editor</title> </head> <body> <textarea id="text"></textarea> </body> </html>JavaScript:
let text=document.getElementById('text') let xhr=new XMLHttpRequest() function sendRequest(tobeSend,writeResponse) { xhr.open('POST','/files/file.txt',false); if(!tobeSend) { //if `tobeSend` not null xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); } xhr.send(tobeSend); if(writeResponse) { text.value=xhr.responseText; } } sendRequest(null,true) text.addEventListener('input',function(e){sendRequest(text.value,false)}) setInterval(function(){let c={start:text.selectionStart,end:text.selectionEnd};sendRequest(null,true);text.setSelectionRange(c.start,c.end)},200)//fresh the code every 200 millisecondPython/frasco:
@app.route('/files/file.txt') def file(): if request.method=='POST': if request.form.text: with open('files/file.txt','w') as f: f.write(str(request.form.text)) with open('files/file.txt') as f: return f.read()Nota: Lo sé, no debería usar sync xhr, pero cuando envío una solicitud asíncrona y escribo un texto, la función asíncrona que regresa elimina el texto escrito (si alguien conoce una solución asíncrona, realmente lo agradecería).
Desde entonces he descubierto el problema:
Cuando envío los datos "text=" , request.form.get("text") devuelve '' , y el valor booleano es False .
Así que cambié el código de la siguiente manera:
@app.route('/files/file.txt') def file(): if request.method=='POST' or request.form.get("text")=='': #intead of `if request.form.get("text")` if request.form.text: with open('files/file.txt','w') as f: f.write(str(request.form.text)) with open('files/file.txt') as f: return f.read()