如何在 Django 中使用 jQuery/Ajax 发布?

2022-01-31 00:00:00 python django post jquery ajax

我正在尝试在 Django 中使用 jQuery/AJAX 发布数据,但遇到了麻烦.当我运行下面的代码并单击测试"按钮时,整个页面会再次重新加载,这不是我想要发生的(这就是我使用 AJAX 的原因).

I am trying to POST data using jQuery/AJAX in Django and am having trouble. When I run the code below and click on the 'test' button, the entire page re-loads again, which isn't what I want to happen (that's why I'm using AJAX).

我也无法确认 AJAX 请求正在进入 Django 视图.

I'm also not able to confirm the AJAX request is getting to the Django view.

我已对 return false 和 event.preventDefault() 进行了编辑.未加载新页面,但我仍然无法在 <div id='message'> 字段中看到更新后的文本.我不确定数据是否正在发送.我在控制台中看到:

I've made the edits for return false and event.preventDefault(). A new page doesn't load, but I'm still not able to see the updated text in the <div id='message'> field. I'm not sure if the data is getting sent. I'm seeing in the console:

POST /edit_favorites/ HTTP/1.1" 403 2294

views.py:

from django.shortcuts import render_to_response
from django.http import HttpResponse

def edit_favorites(request):
    if request.is_ajax():
        message = "Yes, AJAX!"
    else:
        message = "Not Ajax"
    return HttpResponse(message)

urls.py:

url(r'^edit_favorites/', 'edit_favorites'),

HTML:

<form method='post' id='test'>
  <input type="hidden" value="video34"/>
  <input type='submit' value='Test button'/>
  <div id='message'>Initial text</div>
</form>

JavaScript:

$(document).ready(function () {
  $("#test").submit(function (event) {
    event.preventDefault();
    $.ajax({
      type: "POST",
      url: "/edit_favorites/",
      data: {
        'video': $('#test').val() // from form
      },
      success: function () {
        $('#message').html("<h2>Contact Form Submitted!</h2>")
      }
    });
    return false;
  });
});

有什么建议吗?

推荐答案

错位 return false;.它应该在 .submit() 函数的末尾.所以向上移动一行:

Misplaced return false;. It should be at the end of .submit() function. So move it one line upwards:

$(document).ready(function () {
  $("#test").submit(function (event) {
    $.ajax({
      type: "POST",
      url: "/edit_favorites/",
      data: {
        'video': $('#test').val() // from form
      },
      success: function () {
        $('#message').html("<h2>Contact Form Submitted!</h2>")
      }
    });
    return false; //<---- move it here
  });

});

更新:

关于问题 POST/edit_favorites/HTTP/1.1" 403 2294.查看与您的问题相似的帖子:

About the issue POST /edit_favorites/ HTTP/1.1" 403 2294. Check on this post which looks similar to your issue:

  • Django jQuery 发布请求

相关文章