Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

python - How do I POST with jQuery/Ajax in Django?

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).

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

EDIT: 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;
  });
});

Any advice?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
  });

});

UPDATE:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...