我正在尝试向名为getToken()的视图发送ajax请求。我不确定为什么它不起作用。控制台输出“0:”。如果我在我的主视图中包含代码,这是从它进行调用的页面,它会将页面更改为json输出,而不是我告诉它的文档。即使它在urls文件中设置并且我的ajax url设置为该url,它也根本不调用getToken。
当用户在其配置文件中单击创建令牌时,它将向getToken发送ajax请求,并在输出中的页面上返回该输出。因此,用户可以将该密钥提供给他的朋友,以便他们可以添加他或发送电子邮件或发送密钥。
HTML
{% load staticfiles %}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script {% static "ChompMe/jquery.js" %}></script>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>
<script type="text/javascript">
$(document).ready(function() {
$("#create_token").click(function() {
var csrf = '{{ csrf_token }}';
$.ajax({
type: 'POST' ,
url: '/gettoken',
datatype: 'json' ,
async: true,
data:{
csrfmiddlewaretoken: '{{ csrf_token }}',
create_token: 'create_token',
},
success: function(json) {
console.log(csrf);
console.log(json.message);
document.getElementById('output').innerHTML = (json.message);
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
document.getElementById('output').innerHTML = "Token:" + " Request Failed.";
}
});
});
});
</script>
<title>ChompMe
{% block title %}{% endblock %}</title>
</head>
<body>
{% block content %}{% endblock %}
<form method='POST' >
{% csrf_token %}
<button id='create_token' name = 'create_token' value='create_token' > Create Token </button>
</form>
<p id='output'>
Token:
</p>
</body>
</html>
Urls.py
urlpatterns = patterns('',
url(r'^$', 'django.contrib.auth.views.login'),
url(r'^logout/$', logout_page),
url(r'^accounts/login/$', 'django.contrib.auth.views.login'), # If user is not login it will redirect to login page
url(r'^register/$', register),
url(r'^home$', home),
url(r'^register/success/$', register_success),
url(r'^admin/', include(admin.site.urls)),
url(r'^gettoken$', getToken),
url(r'^[A-Za-z0-9_.]+$', friends),
)
Views.Py
@login_required
@csrf_protect
def getToken(request):
print 'getToken'
post_data = request.POST.copy()
username = request.user
if request.POST.has_key('create_token'):
datetimes = datetime.now()
enc_token = base64.urlsafe_b64encode(str(request.user) + str(datetimes))
token = enc_token
context = {'token':token}
return HttpResponse(json.dumps(context),content_type="application/json")
@login_required
@csrf_protect
def home(request):
print 'home'
post_data = request.POST.copy()
username = request.user
if request.POST.has_key('create_token'):
datetimes = datetime.now()
enc_token = base64.urlsafe_b64encode(str(request.user) + str(datetimes))
token = enc_token
context = {'token':token}
return HttpResponse(json.dumps(context),content_type="application/json")
user_data = UserProfile.objects.filter(username=str(request.user))
print user_data
context = {'user': request.user,
'user_data':user_data,
}
return render_to_response('home.html',context , RequestContext(request))
答案 0 :(得分:0)
将/gettoken
更改为/gettoken/
。