Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 有没有更好的方法来检查AJAX请求的值是否有效?_Jquery_Python_Ajax_Django - Fatal编程技术网

Jquery 有没有更好的方法来检查AJAX请求的值是否有效?

Jquery 有没有更好的方法来检查AJAX请求的值是否有效?,jquery,python,ajax,django,Jquery,Python,Ajax,Django,我正在为Django应用程序构建AJAX后端,我不知道是否构建正确。目前,为了接受整数值,我需要使用int()将它们转换成整数,这会引发异常,如果我不应用太多的样板文件,结果总是500。这导致我的代码看起来比我想要的稍微混乱,我不知道我是否做得正确。这是应用程序中的示例AJAX视图: @ajax_required def poll(request): try: last_id = int(request.POST.get('last_id')) feed_

我正在为Django应用程序构建AJAX后端,我不知道是否构建正确。目前,为了接受整数值,我需要使用int()将它们转换成整数,这会引发异常,如果我不应用太多的样板文件,结果总是500。这导致我的代码看起来比我想要的稍微混乱,我不知道我是否做得正确。这是应用程序中的示例AJAX视图:

@ajax_required
def poll(request):
    try:
        last_id = int(request.POST.get('last_id'))
        feed_type = request.POST['feed_type']
    except (KeyError, TypeError):
        return HttpResponseBadRequest()

    if feed_type == 'following' and request.user.is_authenticated():
        posts = Post.get_posts(user=request.user, after_id=last_id)
        return JsonResponse({
            'html': render_to_string('posts/raw_posts.html', {'posts': posts}),
            'count': posts.count()
        })

    return HttpResponseForbidden()

如您所见,我必须做大量的样板文件,并消除语言本身的一些异常,这与我有关,它们来自PHP背景。是否有更好的方法来实现这一点,或者我是否做得正确?

如果您不反对使用框架,它将为您处理序列化和反序列化,那么除了简单的类型检查之外,定义自定义验证非常容易,而且非常棒。汤姆·克里斯蒂甚至还和德扬戈一起使用

编辑: 如果您选择使用它,您的代码将更像这样:

from rest_marshmallow import Schema, fields

class FeedSchema(Schema):
    last_id = fields.Integer()
    feed_type = fields.String()

@ajax_required
def poll(request):
    try:
        # Validate request
        serializer = FeedSchema(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data
        # Return posts
        if data['feed_type'] == 'following' and request.user.is_authenticated():
            posts = Post.get_posts(user=request.user, after_id=data['last_id'])
            return JsonResponse({
                'html': render_to_string('posts/raw_posts.html', {'posts': posts}),
                'count': posts.count()
            })
        # The user isn't authenticated or they requested a feed type they don't have access to.
        return HttpResponseForbidden()
    except ValidationError as err:
        return HttpResponseBadRequest(err.messages)

捕获一个键错误并忘记if,使用
请求.POST[“last_id”]
,是什么引起了
类型错误?@padraiccnningham这种方法的问题是当类型转换为int时,它会引起类型错误。当铸造时,它应该为bad引发一个ValueErrorinput@PadraicCunningham嗯,那很好。会改变的。编辑:Done@PadraicCunningham非常感谢您的观察,现在将进行编辑。看起来很像Django表单,我正在挖掘它。我一定会试试的。谢谢