Ajax GET数据返回“无” [英] Ajax GET data returning 'None'
问题描述
这是我的ajax函数:
Here's my ajax function:
$('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
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'%}
删除,那么它记录正确的数据。任何原因是什么问题?
The console.log(data.username_clicked)
doesn't log anything. But if I take away the {% url 'raise_profile' %}
in the template, then it logs the correct data. Any reason what the problem is?
编辑:
查看:
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:
url(r'^(?P<category>\w+)/(?P<id>\d+)/', article, name='article'), #original view
url(r'^raise_profile/', raise_profile, name='raise_profile'),
编辑2:将数据发送回模板我已经尝试过:
To send data back to template I've tried these:
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
。任何意图为什么数据没有发送到我的模板?
and nothing shows up. But when I print profileAge in my view it returns 4
. Any idea why the data isn't being sent to my template?
推荐答案
这是因为当您点击 href 元素,网址为 {%url'raise_profile'%} ,
然后窗口的位置更改为www.example.com/raise_profile/
在这行中:
This is because when you click on a href element with url as {% url 'raise_profile' %}, Then the location of window changes to something like www.example.com/raise_profile/ and in this line :
var url = window.location.href.split('?')[0];
你是在吐痰网址?它现在不存在于窗口位置url中。
所以如果你希望这个数据发送到 raise_profile url,那么只是更新它:
You are spitting url after ? which is now not present in window location url. So if you want this data to send to raise_profile url then just update it as it is :
$('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)
}
})
});
这篇关于Ajax GET数据返回“无”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!