• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

224
Views
Django + Ajax: ¿por qué redirige a una nueva URL y muestra la respuesta en el navegador?

Según tengo entendido, ajax podría usarse para evitar que la página se vuelva a cargar/actualizar/redireccionar después de enviar una solicitud al servidor. Sin embargo, mi código se redirigirá para mostrar la respuesta JSON. Usé e.preventDefault() y no funcionó. ¿Hay algo que esté haciendo mal?

Mi código Django se ve así: views.py:

 def projects(request): if request.method == 'POST': task_id = request.POST.get('task_id') myUser = User.objects.get(pk=request.user.id) myTask = Task.objects.get(pk = task_id) myTask.claimed.add(myUser) #add the user to the task return JsonResponse({'status': 'ok'}) projects = Project.objects.all() tasks = Task.objects.all() open_tasks = tasks.filter(status='Created') proj_dict = {} context = { 'projects' : projects, 'tasks' : tasks, 'open_tasks' : open_tasks, } return render(request, 'projects/projects.html', context)

Mi HTML:

 <form action="{% url 'projects:' %}" method="POST" class='join-form' id='{{task.id}}'> {% csrf_token %} <input type="hidden" name="task_id" value={{task.id}}> <button type="submit" class=" claim-font claim-button"> Join </button> </form>

Esa llamada ajax:

 <script> $(document).ready(function () { $('#join-form').on('submit', function (e) { e.preventDefault(); e.stopPropagation(); const url = $(this).attr('action'); console.log("here we are"); const task_id = $(this).attr('id'); $.ajax({ type: 'POST', dataType: "json", headers: { 'X-CSRFToken': csrftoken }, url: url, data: { csrfmiddlewaretoken: '{{ csrf_token }}', task_id: task_id, }, success: function (response) { alert(data); console.log("here we are"); }, error: function (response) { console.log('error', response); alert("shit") } }) return false; }); }); </script>

Parece que ajax se asegurará de que mi navegador no redirija/recargue/actualice después de hacer clic en el botón Enviar, y solo cambie el lado del servidor. Sin embargo, mi navegador muestra: {"status": "ok"}

¡Cualquier idea es muy apreciada!

almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Noté que tienes un atributo de clase para tu formulario. Cambie su selector JQuery de $('#join-form') a $('.join-form') para atributos de clase

 <script> $(document).ready(function () { $('.join-form').submit(function(e) { e.preventDefault(); // write your code here }); }); </script>
almost 3 years ago · Juan Pablo Isaza Report

0

Debe cambiar el tipo de botón de "enviar" a "botón"

almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error