在django或者ajax项目中经常会用到使用post向后端提交信息,前端一般都会用ajax的方式进行提交

前端提交数据到后端,后端进行数据验证,如果验证通过,则返回status=200,如果没有验证通过,则返回错误信息

form代码:

# django
class FormMixin(object):
    '''
    get_errors: 获取错误信息并返回成json
    '''
    def get_errors(self):
        if hasattr(self,'errors'):
            errors = self.errors.get_json_data()
            new_errors = {}
            for key, message_dicts in errors.items():
                messages = []
                for message in message_dicts:
                    messages.append(message['message'])
                new_errors[key] = messages
            return new_errors
        else:
            return {}

class Myform(forms.Form,FormMixin)
    """表单"""
    ...
    ...

# flask代码

from wtforms import Form
"""message:将错误代码返回,forms直接继承BaseForm"""
class BaseForm(Form):
    def get_error(self):
        message = self.errors.popitem()[1][0]
        return message

    def validate(self):
        return super(BaseForm, self).validate()

将forms代码提取出来后,返回内容最好是一定规则的

from django.http import JsonResponse
# 如果是flask就是用  from flask import jsonify

class HttpCode(object):
    ok = 200
    paramserror = 400
    unauth = 401
    methoderror = 405
    servererror = 500

# {"code":400,"message":"","data":{}}
def result(code=HttpCode.ok,message="",data=None,kwargs=None):
    json_dict = {"code":code,"message":message,"data":data}

    if kwargs and isinstance(kwargs,dict) and kwargs.keys():
        json_dict.update(kwargs)

    return JsonResponse(json_dict)


def ok():
    return result()


def params_error(message="",data=None):
    return result(code=HttpCode.paramserror,message=message,data=data)

def unauth(message="",data=None):
    return result(code=HttpCode.unauth,message=message,data=data)

def method_error(message='',data=None):
    return result(code=HttpCode.methoderror,message=message,data=data)

def server_error(message='',data=None):
    return result(code=HttpCode.servererror,message=message,data=data)

这个是将返回内容指定成一个restful风格的样子,在视图中直接调用就行了

return restful.ok()
or
return restful.params_error(message=form.get_errors())

前端使用的ajax我们要封装一下,方便使用的时候直接调用

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var web_ajax = {
    'get': function (args) {
        args['method'] = 'get';
        this.ajax(args);
    },
    'post': function (args) {
        args['method'] = 'post';
        this.ajax(args);
    },
    'ajax': function (args) {
        this._ajaxSetup();
        $.ajax(args);
    },
    '_ajaxSetup': function () {
        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (!/^(GET|HEAD|OPTIONS|TRACE)$/.test(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
                    layer.load(1, {
                        shade: [0.7, '#000'] //0.1透明度的白色背景
                    });
                }
            },
            complete: function () {
                layer.closeAll('loading')
            },
        });
    }
};

在提交的时候直接按照以下就可以了

$(function () {
    web_ajax.post({
        "url":"xxx",
        "data":{
            "xx":"xx"
        }
        "success":function(data){
            if (data.code=='200'){
             }else {
                            var message = String(data.message.message)
                            layer.msg(message)
                        }
        },
        'fail':function (error) {
                        console.log('网络错误')
                    }
    })

}
最后修改:2020年7月27日 16:17