【问题标题】:Ajax GET data returning 'None'Ajax GET 数据返回“无”
【发布时间】:2017-06-08 19:08:12
【问题描述】:

这是我的 ajax 函数:

$('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。知道为什么数据没有发送到我的模板吗?

【问题讨论】:

  • 你在 ajax 调用中得到“用户名”吗?请先检查“用户名”变量控制台。记录或提醒它,然后检查你得到了什么。
  • 刚刚在var username = $(this).html(); 下添加了console.log(username),是的,它记录了正确的数据(用户名)。

标签: jquery python ajax django django-views


【解决方案1】:

这是因为当您点击 a href 元素时,其 url 为 {% url 'raise_profile' %}, 然后窗口的位置更改为类似 www.example.com/raise_profile/ 在这一行:

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

你是在吐 url 吗?现在不在窗口位置 url 中。 因此,如果您希望将此数据发送到 raise_profile url,那么只需按原样更新它:

$('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)
        }
    })
});

【讨论】:

  • 谢谢你的作品。你能告诉我是否可以在保持相同的先前 URL 的同时调用 raise_profile 函数?因为raise_profile() 应该是一个 AJAX 调用,所以我不想在调用它时更改 URL。我会将我的原始 URL 和原始视图放入我的编辑中。
  • @Zorgan 是的,您可以轻松做到这一点。只是不要将 {% url 'raise_profile' %} 放在 ahref 标记中,并将重定向 URL 放在 raise_profile 视图中的 print(username_clicked) 行之后。
  • 如果我不将{% url 'raise_profile' %} 放在ahref 标签中,那么它就不会调用raise_profile() 视图?
  • @Zorgan 返回 JSON 响应并在 成功中获取该数据:function (data) { console.log(data) }
  • 完美。谢谢你的帮助。
猜你喜欢
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
  • 2013-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
相关资源
最近更新 更多