【发布时间】:2020-04-14 00:55:17
【问题描述】:
我有一个令牌,需要将其传递给 API(在 views.py 中创建),以便取回生成的时间。我已使用 Simple-JWT 生成令牌,但无法将其发送到指定的 URL。请参阅下面的代码:
models.py:
class My_time(models.Model):
id= models.ForeignKey(User, on_delete = models.CASCADE)
time = models.DateTimeField()
views.py:
#API to get back time (if existing) or create a new time and send it back to the HTML page via AJAX.
class TimeAPI(generics.ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = MySerializer
def get_queryset(self, request):
current_time = timezone.now()
if (My_time.objects.filter(time=current_time) in (None, '')):
time = My_time.objects.create(time=current_time) #saves it to my database
else:
pass
data = My_time.objects.values_list('time', flat=True)
return data #should return the data to the HTML page
serializers.py:
class MySerializer(serializers.ModelSerializer):
class Meta:
model = My_time
fields = ('time')
urls.py:
urlpatterns = [
# ...,
path('time_api/',TimeAPI.as_view(), name = 'time_api'),
]
interface.html:
{% block content %}
<form method="POST">
<button type="button" class="btn btn-outline-info" id ='get_time'> Punch In </button>
<h4 id='display_time'></h4>
</form>
{% endblock content%}
JS 代码(在 HTML 页面内):
{% block javascript %}
<script type="text/javascript">
$('#get_time').click(function () {
var access_token = localStorage.getItem('access'); #stored the token before in localStorage
$.ajax({
cache: false,
url: {% url 'time_api' %},
method: 'GET',
// datatype: 'json',
headers: { "Authorization": 'Bearer ' + access_token }
success: function(data) {
console.log(headers);
document.getElementById("display_time").innerHTML(data);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log("No data");
}
});
});
</script>
{% endblock javascript %}
单击我的 HTML 页面中的按钮后,我无法返回生成的时间。事实上,什么也没有发生。
这是 JS 控制台中的错误:
Uncaught SyntaxError: Unexpected identifier
它指向AJAX中的成功函数:
headers: { "Authorization": 'Bearer ' + access_token }
success: function(data) {
console.log(headers);
..... //remaining code
有人可以解释什么是错的吗?谢谢你
【问题讨论】:
标签: jquery django ajax django-rest-framework jwt