有条件地创建ajax url参数以与jQuery Validate一起使用

时间:2015-03-17 20:21:41

标签: javascript jquery ajax jquery-validate

我的jquery验证脚本存在问题。基本上,我需要的是:基于字符串的最后部分(isAdd),当用户单击发送按钮时,脚本将在if或else语句之间进行选择并发送ajax请求以验证输入字段。服务器将发送一个真或假标志。如果为true,表单将提交,如果为false,表单将不会提交。我认为我的代码表现得更好:

// Waiting for the btnSave to be clicked
$(document).on('click', '.btnSave', function (event) {

    // Here I get the action value in the form tag, split it in chunks and 
    // get the last element in the array, assigned it to the isAdd variable
    var isAdd = $('#customerAddressForm').prop("action").split("/").pop();

    // If the variable value is the same as "Shipping", it means that it's 
    // the edit button that was clicked
    if (isAdd == "Shipping") {

        // I add the following rules to the input with id "inputAddressName"
        $('input[id="inputAddressName"]').rules("add", {
            required: true,
            noSpace: true,

            // Here I do the Ajax call, the value in the customerAddressId 
            // is appended to the url. Example: 
            // https://localhost:8443/mysite/useraccount/isExistingAddressName?addressName=Bill1&customerAddressId=1232. 
            // This get a true/false flag from the server

            remote: {
                url: "https://localhost:8443/mysite/usersite/addresses/isExistingAddressName",
                contentType: "application/json; charset=utf-8",
                data: {
                    customerAddressId: function () {
                        return $("#customerAddressForm").prop("action").split("/").pop();
                    }
                }
            }
        });

    // If the variable value is not the same as "Shipping", it means that 
    // it's the add button that was clicked
    } else {
        $('input[id="inputAddressName"]').rules("add", {
            required: true,
            noSpace: true,

            // Here I do the Ajax call for the add, a hardcoded value (-10) 
            //for the customerAddressId is appended to the url. Example: 
            // https://localhost:8443/mysite/useraccount/isExistingAddressName?addressName=Bill1&customerAddressId=-10. 
            //This get a true/false flag from the server.
            remote: {
                url: "https://localhost:8443/mysite/usersite/addresses/isExistingAddressName",
                contentType: "application/json; charset=utf-8",
                data: {
                    customerAddressId: function () {
                        return $("-10");
                    }
                }
            }
        });
    }


    $('#customerAddressForm').validate({

        ignore: 'input[type=hidden], .select2-input, .select2-focusser',
        rules: {
            "address.addressLine1": {
                required: true
            },
            "address.addressLine2": {
                number: true
            }
        },
        messages: {
            "addressName": {
                required: "Please enter an address name",
                remote: "Address name already taken. Please enter another one"
            },
                "address.addressLine1": {
                required: "Please enter your street address"
            },
                "address.addressLine2": {
                number: "Please enter only numbers"
            }
        },
        highlight: function (element) {
            $(element).closest('.control-item').addClass('has-error');
        },
        unhighlight: function (element) {
            $(element).closest('.control-item').removeClass('has-error');
        },
        errorElement: 'small',
        errorClass: 'help-block',
        errorPlacement: function (error, element) {
            error.insertAfter(element);
        }
    });
});

这是否是根据if / else语句传递远程选项中的url的正确方法?它不起作用我得到:Uncaught TypeError:无法读取属性'设置'未定义的。

1 个答案:

答案 0 :(得分:0)

您的代码......

$(document).on('click', '.btnSave', function (event) {
    ....
    if (isAdd == "Shipping") {
        $('input[id="inputAddressName"]').rules("add", {
            ....
        });
    } else {
        $('input[id="inputAddressName"]').rules("add", {
            ....
        });
    }

    $('#customerAddressForm').validate(....);  // <-initializes plugin

});
  

我只得到“无法读取未定义的属性'设置'”

您的代码中有一些致命错误......

  1. 您尝试在之前使用.rules()方法在表单上初始化插件;这可能是您的错误消息的来源。 .validate()方法仅用于插件的初始化

  2. 由于.validate()方法用于在表单上初始化插件,因此只能在 中调用 (在DOM就绪事件中) ,永远将其置于click处理程序中。

  3. 这样做......

    $(document).ready(function() {
    
        $('#customerAddressForm').validate(....); // <-initializes plugin
    
        $(document).on('click', '.btnSave', function (event) {
            ....
            if (isAdd == "Shipping") {
                $('input[id="inputAddressName"]').rules("add", {
                    ....
                });
            } else {
                $('input[id="inputAddressName"]').rules("add", {
                    ....
                });
            }
        });
    
    });