2017-01-24 114 views
0

这里是我的ajax功能:阿贾克斯GET数据返回 '无'

$('a.username').on('click', function() { 

    var username = $(this).html(); 
    var url = window.location.href.split('?')[0]; 

    $.ajax({ 
     type: 'GET', 
     url: url, 
     data: { 
      username_clicked: username, 
      csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val() 
     }, 
     success: function (data) { 
      console.log(data.username_clicked) 
     } 
    }) 
}); 

而且模板:

<h3><a href="{% url 'raise_profile' %}" class="username">{{ i.author }}</a></h3> 

网址

url(r'^raise_profile/', raise_profile, name='raise_profile'), 

和看法:

def raise_profile(request): 
    if request.method == 'GET': 
     print('get') #prints 'get' 
     username_clicked = request.GET.get('username_clicked') 
     print(username_clicked) #prints 'None' 

    return render(request, 'article.html', {}) 

console.log(data.username_clicked)不记录任何东西。但是,如果我在模板中取走{% url 'raise_profile' %},那么它会记录正确的数据。任何原因是什么问题?

编辑:

观点:

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(): 
     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): 

    username_clicked = request.GET.get('username_clicked') 
    print(username_clicked) 
    if request.is_ajax(): 
     profile = Profile.objects.get(username=username_clicked) 
     print('Age:', profile.age) 

    return HttpResponse() 

网址:

url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article'), #original view 
url(r'^raise_profile/', raise_profile, name='raise_profile'), 

EDIT2:为了将数据发送回模板,我已经试过这些:

def raise_profile(request): 
    username_clicked = request.GET.get('username_clicked') 
    if request.is_ajax(): 
     profile = Profile.objects.get(username=username_clicked) 
     print('Age:', profile.age) 
     profileAge = profile.age 
     response_data = json.dumps({'profile_age': profileAge}) 
     return HttpResponse(response_data, content_type='application/json') 

def raise_profile(request): 
    username_clicked = request.GET.get('username_clicked') 
    if request.is_ajax(): 
     profile = Profile.objects.get(username=username_clicked) 
     print('Age:', profile.age) 
     profileAge = profile.age 
     return JsonResponse('profileAge': profileAge) 

base.html文件

<p class="profile_age">{{ profileAge }}</p> 

,并没有显示出来。但是,当我在我的视图中打印profileAge时,它将返回4。任何想法为什么数据没有被发送到我的模板?

+0

你在Ajax调用获得“用户名”。请首先检查'用户名'变量console.log它或提醒它,并检查你得到。 –

+0

刚刚在'var username = $(this).html();'下面添加了'console.log(username)',是的,它记录了正确的数据(用户名)。 – Zorgan

回答

1

这是因为当你用URL点击A HREF元素{%URL 'raise_profile' %}, 随后的窗口的位置发生变化,以类似www.example.com/raise_profile/ 和在这一行中:

var url = window.location.href.split('?')[0]; 

你在随地吐痰网址吗?这在窗口位置URL中不存在。 所以,如果你想在这个数据发送给raise_profile网址,然后只需更新它,因为它是:

$('a.username').on('click', function() { 

    var username = $(this).html(); 
    var url = "/raise_profile/"; 

    $.ajax({ 
     type: 'GET', 
     url: url, 
     data: { 
      username_clicked: username, 
      csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val() 
     }, 
     success: function (data) { 
      console.log(data.username_clicked) 
     } 
    }) 
}); 
+0

谢谢你的作品。你能告诉我,在保持原先的URL的同时是否可以调用'raise_profile'函数?因为'raise_profile()'应该是一个AJAX调用,所以我不想在我调用它时更改URL。我将我的原始网址和原始视图添加到我的修改中。 – Zorgan

+1

@ Zorgan是的,你可以轻松地做到这一点。只要不要将{%url'raise_profile'%}放入ahref标记中,并在raise_profile视图的** print(username_clicked)**行之后将重定向URL放到当前页面。 –

+0

如果我不把'{%url'raise_profile'%}'放在ahref标记中,那么它不会调用'raise_profile()'视图? – Zorgan