Skip to main content
 首页 » 编程设计

jquery之如何使用 jQuery/AJAX 访问 views.py 中的变量

2025年05月04日37pengyingh

编辑

当我编写 print request.POST['video'] 时,即使“video”有值,控制台也不会打印任何内容。我在 javascript 中错误地得到了错误的值吗?我正在尝试显示“video34”(隐藏字段中的值)。

原创

我正在尝试在 Django 中使用 jQuery/AJAX 发布数据,但遇到了问题。如何访问 views.py 中的“video”变量?当我在 views.py 中写入“打印视频”时,我在控制台中收到一条错误消息,显示 POST/edit_favorites/HTTP/1.1"500 10113。

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

网址配置:

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 中一样。