AJAX调用无法在Django中向API发送令牌

时间:2019-12-22 10:24:45

标签: jquery django ajax django-rest-framework jwt

我有一个令牌,需要将其传递给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

有人可以解释出什么问题吗?谢谢

5 个答案:

答案 0 :(得分:0)

尝试使用浏览器开发人员工具并检查js控制台输出,并将其包括在此处,并尝试覆盖CBV的get方法并检查if self.request.is_ajax并返回所需的数据。可能是个问题

答案 1 :(得分:0)

修改错误处理程序,使其仅接受data参数并将其记录到控制台。

错误在js函数中

答案 2 :(得分:0)

定义一个新方法web: gunicorn django_project.wsgi ,然后在js中使用def get(self,request): queryset=self.get_queryset()# construct your html response and construct a json response and returñ that访问数据值

答案 3 :(得分:0)

定义一个新方法def get(self,request): queryset=self.get_queryset()# construct your html response and construct a json response and returñ that,然后在js中使用`data.value

访问数据值

答案 4 :(得分:0)

from rest_framework.response import Response

def get(self, response):
    data = self.get_queryset()
    # assuming data is a dict object
    return Response(data)