0

我正在寻找建议,以确保我使用普遍接受的 js 准则来使用回调和 javascript 编码。下面列出的是两个链接在一起的功能。基本上它是在创建实体之前需要完成的检查列表。我不希望最终版本使用 ajax POST,但它是测试所有错误处理的好方法。

建议或建议将不胜感激!我将给予最好的解释和批评的答案。

function relationship_check(app_label, model, company_id, params, form, callback_function){
    // This will check to see if a relationship exists.  This works even on new objects.
    kwargs = $.extend({}, params);
    kwargs['app_label'] = app_label;
    kwargs['model'] = model;
    kwargs['relationship__company'] = company_id;
    kwargs['error_on_objects_exists_and_no_relation'] = true;
    ajax_req = $.ajax({
        url: "{% url 'api_get_discover' api_name='v1' resource_name='relationship' %}",
        type: "GET",
        data: kwargs,
        success: function(data, textStatus, jqXHR) {
            callback_function(form, params)
        },
        error: function(data, textStatus, jqXHR) {
            results = $.parseJSON(data.responseText)
            if (results['object_exists'] && ! results['relationships_exists']){
                django_message(results['create_string'], "info");
            } else {
                django_message(results['error'], "error");
            }
            return false
        }
    })
    return false
};

function create_community(form, data){
    var self = $(this),
    ajax_req = $.ajax({
        url: self.attr("action"),
        type: "POST",
        data: data,
        success: function(data, textStatus, jqXHR) {
            django_message("Saved successfully.", "success");
        },
        error: function(data, textStatus, jqXHR) {
            var errors = $.parseJSON(data.responseText);
            $.each(errors, function(index, value) {
                if (index === "__all__") {
                    console.log(index + " : " + value )
                    django_message(value[0], "error");
                } else {
                    console.log(index + " : " + value )
                    apply_form_field_error(index, value);
                }
            });
        }
    });
}

$(document).on("submit", "#community_form", function(e) {
    e.preventDefault();
    clear_form_field_errors("#community_form");
    var data = {
        name: $(this).find("#id_name").val(),
        city: $(this).find("#id_city").val(),
        cross_roads: $(this).find("#id_cross_roads").val(),
        website: $(this).find("#id_website").val(),
        latitude: $(this).find("#id_latitude").val(),
        longitude: $(this).find("#id_longitude").val(),
        confirmed_address: $(this).find("#id_confirmed_address").val()
     };
    console.log(data)
    relationship_check(
            'community', 'community', '{{ request.user.company.id }}',
            data, "#community_form", create_community);
});
4

0 回答 0