如何在Python(Django)中处理Ajax数据

2024-06-13 20:05:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过Ajax将前端数据(表单输入)推送到服务器。为此,我创建了一个Ajax post请求,但是我非常不稳定。。。 在我第一次尝试时,我经常收到python的错误

Ajax调用:

//Get journey time for the stated address
    jQuery.ajax({
        type: 'post',
        url: 'http://127.0.0.1:8000/termin/get-journey-time/',
        data: {
            'method': 'get_journey_time',
            'mandant_id': 1,
            'customer_address': customer_address,
            'staff_group': staff_group_id
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("Error")
        },
        timeout: 120000,
    });

我已经用Python创建了一个视图,我想在其中做一些事情(视图.py)你知道吗

class get_journey_time(generics.ListAPIView):
    """
    Handle Ajax Post to calculate the journey time to customer for the selected staff group
    """
    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):
        print(request)

在我的url路由文件中,我有以下代码行(网址.py)你知道吗

urlpatterns = [
    XXXXXXXXXXXXXXXXXXXXXXXXX,
    path('termin/get-journey-time/', views.get_journey_time.as_view()),
    XXXXXXXXXXXXXXXXXXXXXXXXX,
    XXXXXXXXXXXXXXXXXXXXXXXXX,
]

我得到了错误代码500:

Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`

我的方法有错误吗?我错过了什么吗?还是完全是垃圾?你知道吗


Tags: thetourlforgettimeaddress错误
2条回答

你可以这样做

from rest_framework.response import Response
from rest_framework.views import APIView


class get_journey_time(APIView):
    # ListAPIView is used for read-only endpoints
    #
    """
    Handle Ajax Post to calculate the journey time to customer for the selected staff group
    """
    permission_classes = (AllowAny,)

    def post(self, request, *args, **kwargs):
        # you can get the posted data by request.data
        posted_data = request.data
        data = {"test": "test"}
        return Response(data)

您可以获取发布的数据并使用序列化程序。您可以开始学习使用序列化程序from here

示例序列化程序代码可以如下所示

from rest_framework import serializers


class DummySerializer(serializers.Serializer):
    name = serializers.CharField()
    mobile_number = serializers.CharField(required=False)

然后在get_journey_time类的post方法中使用它

设置.py。你知道吗

Note: You can define many of these (based on requirements and needs) but here we only need JSON related.

As a reference, you can check my repo's this file https://github.com/hygull/p-host/blob/master/src/pmt_hostel_app/views.py. I have used function based views, just ignore the code inside it and focus on request.data and also check related HTML files.

REST_FRAMEWORK = {
    'DEFAULT_PARSER_CLASSES': (
        'rest_framework.parsers.JSONParser',
    ), 
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer', 
   )
}

通过这种方式,您将能够访问以字典形式发布的数据,可以使用请求.数据在视图中。你知道吗

最后,从post()方法返回响应。默认情况下,函数/方法的返回类型为None,您只需打印请求。你知道吗

检查下面提到的链接,它将帮助你很多。你知道吗

在客户机代码中,我的意思是在JavaScript代码中,也定义一个success回调(您刚刚定义了error回调)。你知道吗

请评论,如果你卡住了。你知道吗

相关问题 更多 >