Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
error de sintaxis al usar la búsqueda en Javascript

Estoy haciendo formularios en Django y JavaScript.

Necesito mostrar un formulario después de hacer clic en un botón, que será respondido y devolverá (en formato JSON) una lista con las respuestas.

Mi código index.js

 document.querySelector("#create-blank-form").addEventListener("click", () => { const csrf = Cookies.get('csrftoken'); fetch('/form/create', { method: "POST", headers: {'X-CSRFToken': csrf}, body: JSON.stringify({ title: "Untitled Form" }) }) .then(response => response.json()) .then(result => { window.location = `/form/${result.code}/edit` }) })

El error, el error apunta a .then(resultado...)

 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise.then (async) (anonymous)

Mis vistas.py

 def create_form(request): print('hi') # Creator must be authenticated # Create a blank form API if request.method == "POST": print('hi') data = json.loads(request.body) title = data["title"] code = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(30)) choices = Choices(choice = "Option 1") choices.save() question = Questions(question_type = "multiple choice", question= "Untitled Question", required= False) question.save() question.choices.add(choices) question.save() form = Form(code = code, title = title, creator=request.user) form.save() form.questions.add(question) form.save() return JsonResponse({"message": "Sucess", "code": code})

mi .html

 <div class="form-template-box"> <img src = "{% static 'Icon/blank-form.png' %}" alt = "Blank form" title = "Blank form" id="create-blank-form"> <span class="form-template-label">Blank Form</span> </div>

mis urls.py

 path('form/create', views.create_form, name="create_form"),

EDITAR

mi problema era con la url, en urls.py, otra parte de mi código por alguna razón estaba influyendo de mala manera. gracias por los comentarios me ayudaron a encontrar el error

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

El error SyntaxError: Unexpected token < in JSON at position 0 dice que el primer carácter de la respuesta es '<' y sugiere que la respuesta dada está en formato XML en lugar de JSON.

Entonces response.json() no funcionará porque la response no es un JSON válido. si lo fuera, el primer carácter sería '{' o '['.

Le sugiero que consola.log() la respuesta para verificar el formato y luego extraer el elemento 'código' que está buscando usando:

 const parser = new DOMParser(); const doc = parser.parseFromString(response, 'text/xml'); const codeYouWant = doc.getElementsByTagName("code")[0].innerHTML;
about 4 years ago · Juan Pablo Isaza Report

0

Creo que su función tiene algunos problemas que devuelven un error en lugar de una respuesta JSON. Entonces en .then(response => response.json()) generará un error. Puede probar el ejemplo a continuación para comprobar el error.

 if request.method == "POST": try: print('hi') data = json.loads(request.body) title = data["title"] code = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(30)) choices = Choices(choice = "Option 1") choices.save() question = Questions(question_type = "multiple choice", question= "Untitled Question", required= False) question.save() question.choices.add(choices) question.save() form = Form(code = code, title = title, creator=request.user) form.save() form.questions.add(question) form.save() return JsonResponse({"message": "Sucess", "code": code}) except Exception as err: return JsonResponse({"message": "Failed", "error": err})

Y

 .then(result => { console.log("DEBUG result: ", result); window.location = `/form/${result.code}/edit` })
about 4 years ago · Juan Pablo Isaza Report

0

mi problema era con la url, en urls.py, otra parte de mi código por alguna razón estaba influyendo de mala manera. gracias por los comentarios me ayudaron a encontrar el error

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!