简体   繁体   中英

How do I access a variable in views.py using jQuery/AJAX?

edit

When I write print request.POST['video'], nothing gets printed in the console even through there is a value for 'video'. Am I incorrectly getting the wrong value in the javascript? I am trying to get the 'video34' (the value in the hidden field) to show up.

original

I am trying to POST data using jQuery/AJAX in Django and am having trouble. How do I access the 'video' variable in the views.py? When I write 'print video' in views.py, I get an error in the console saying POST /edit_favorites/ HTTP/1.1" 500 10113.

views.py

from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

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

urlconf:

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:

<script type="text/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;
       });
       
    });
</script>

它在request.POST['video'] ,就像在普通的 POST 中一样。

In the message you got in the console POST /edit_favorites/ HTTP/1.1" 500 10113 , the "500" is the key. It means there's an error in your server code, most likely. In this case you're trying to 'print' a nonexistent variable. I'm surprised in fact that you don't see a traceback for a NameError somewhere.

I'm not a Django user so maybe someone else can chime in with a better recommendation, but according to the Django docs all the post arguments are in request.POST which is a dict-like object.

I'd suggest checking:

if request.method == 'POST':
    if 'video' in request.POST:
        video = request.POST['video']
        # Do stuff, etc...
    else:
        # Raise an error

That's on the server side. In your HTML you also need to give names to all your form input fields. For example <input name="video" type="hidden" value="video32" /> or the like. You may wish to read up more on HTML form posting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM