Jquery 如何为AJAX请求创建单独的视图函数?

Jquery 如何为AJAX请求创建单独的视图函数?,jquery,python,ajax,django,django-views,Jquery,Python,Ajax,Django,Django Views,我的视图函数变得相当混乱,所以可以从我的视图文件中的单独函数调用我的ajax请求吗 这是我的视图 def article(request, category, id): name = resolve(request.path).kwargs['category'] for a, b in CATEGORY_CHOICES: if b == name: name = a instance = get_object_o

我的视图函数变得相当混乱,所以可以从我的视图文件中的单独函数调用我的ajax请求吗

这是我的视图

def article(request, category, id):

    name = resolve(request.path).kwargs['category']
    for a, b in CATEGORY_CHOICES:
        if b == name:
            name = a
            instance = get_object_or_404(Post, id=id, category=name)

    allauth_login = LoginForm(request.POST or None)
    allauth_signup = SignupForm(request.POST or None)

    #comments
    comment = CommentForm(request.POST or None)
    ajax_comment = request.POST.get('text')
    comment_length = len(str(ajax_comment))

    comment_list = Comment.objects.filter(destination=id)
    score = CommentScore.objects.filter(comment=comment_list)

    if request.is_ajax():
        username_clicked = request.GET.get('username_clicked')
        profile = Profile.objects.get(username=username_clicked)
        if username_clicked:
            print(profile.age)
        if comment.is_valid():
            comment = Comment.objects.create(comment_text=ajax_comment, author=str(request.user), destination=id)
            comment.save()

            score = CommentScore.objects.create(comment=comment)
            score.save()
            username = str(request.user)
            return JsonResponse({'text': ajax_comment, 'text_length': comment_length, 'username': username})
        else:
            print(comment.errors)


    context = {
        'score': score,
        'comment_list': comment_list,
        'comment': comment,
        'instance': instance,
        'allauth_login': allauth_login,
        'allauth_signup': allauth_signup
    }

    return render(request, 'article.html', context)
例如,对于单击的
用户名
,我想将其取出,并在同一个视图文件中创建自己的函数,如下所示:

def raise_profile(request):
    if request.is_ajax():
        username_clicked = request.GET.get('username_clicked')
        profile = Profile.objects.get(username=username_clicked)
        if username_clicked:
            print(profile.age)
            return HttpResponse()
这可能吗?请记住,这些都位于相同的URL
URL(r'^(?P\w+/(?P\d+/),article,name='article')

这可能吗

更新功能:

def raise_profile(request):
    if request.is_ajax():
        username_clicked = request.GET.get('username_clicked')
        profile = Profile.objects.get(username=username_clicked)
        if username_clicked:
            print(profile.age)
            response_data = json.dumps({username_clicked})
            return HttpResponse(response_data, content_type='application/json')
是的,这是可能的

只需在urls.py中为AJAX函数指定它自己的URL,并在发布数据时指向该URL即可

URL.py:

url(r'^custom-ajax-function/', 'module.views.raise_profile'), 
您可以返回如下内容:

    response_data = json.dumps({})
    return HttpResponse(response_data, content_type='application/json')
class data_form(forms.Form)
    username = form.CharField() 

def raise_profile(request):
    username_clicked = None 
    if request.method == 'POST':
        form = data_form(request.POST, request.FILES)
        if form.is_valid():
            username_clicked = form.cleaned_data.get('username')
    response_data = json.dumps(username_clicked)
    return HttpResponse(response_data, content_type='application/json')
如有必要,包装json转储中的任何数据

此外,我不确定流行的观点是什么,但我会确保您正在使用django清理您的请求数据。我不确定您的Django版本是否做到了这一点,但我一直使用表单来清理GET/POST数据。我相信获取原始GET数据很容易被注入

编辑: 我相信OP和我在如何发布数据方面有不同的策略。我通过按钮处理程序上的jquery调用处理所有AJAX帖子。因此,在您的HTML中,我将在jquery中执行如下操作:

$('.button_handler').on('click', function(){ 
  //logic
  var posted_username = '...'
  .ajax({
      url: "/custom-ajax-function/",
      type: "POST",
      data: { 
           username: 'posted_username,
          },
      success:function(data) { 
         //Do something if it works, if you want
     }
});
这将允许您将数据直接从网页发布到django函数的url。如果发送数据时遇到问题,可能需要启用,但这很简单,只需将一些javascript设置函数粘贴到页面中即可

还有,这只是我,也许你对Django的理解不同,但我 像这样编写我的处理程序:

    response_data = json.dumps({})
    return HttpResponse(response_data, content_type='application/json')
class data_form(forms.Form)
    username = form.CharField() 

def raise_profile(request):
    username_clicked = None 
    if request.method == 'POST':
        form = data_form(request.POST, request.FILES)
        if form.is_valid():
            username_clicked = form.cleaned_data.get('username')
    response_data = json.dumps(username_clicked)
    return HttpResponse(response_data, content_type='application/json')

is_valid()确保POST数据中没有非法字符或注入脚本

好的,我的模板指向的url如下:
url(r'^raise\u profile/',views.raise\u profile,name='raise\u profile')
,但我收到一个错误,说
raise\u profile没有返回HttpResponse对象。它没有返回任何结果。
你知道为什么吗?我会在我的编辑中发布这个函数。我认为你做的事情与我完全不同,尽管我很犹豫说哪个版本是“正确的”。但我的版本应该能帮你解决这个问题。我希望我的编辑是有帮助的。谢谢,我设法让它工作做一些相当类似你的