Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

181
Vistas
Live code editor - cannot delete first character (using XMLHttpRequest and flask)

I have a live code editor, and I cannot delete the first character, if I select the whole text, and press delete or backspace, it do not do anything.
What can I do?
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 millisecond

Python/flask:

@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()

Note: I know, I should not use sync xhr, but when I send an async request, and I write some text, the returning async function delete the writed text (if somebody know an async solution, I would really appreciate it).

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I have since discovered the problem:
When I send at the data "text=", the request.form.get("text") returns '', and tha boolean value is False.
So I changed the code as below:

@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()
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda