当复选框ID /名称包含连字符时,通过JSON发布数据

时间:2018-01-10 15:32:05

标签: javascript jquery json ajax

我尝试使用postUserData,以便当一个人填写并在我的网站的一个页面上提交表单时,它会将数据提交到我网站上不同页面上的表单。

这一切都奏效,直到我向我的表单引入了一个名为writerep的复选框,因为我的CMS在最终表单上自动生成复选框名称(在这种情况下,引人注目的" custom-1798_0",并且因为该ID / name包含一个连字符,它打破了JSON。其他没有连字符的复选框工作正常。代码如下:

    $('#user_info_form').validate({
submitHandler: function submitHandler(form, e) {
    e.preventDefault();

    var firstname = e.target.firstname.value;
    var lastname = e.target.lastname.value;
    var email = e.target.email.value;
    var country = e.target.country.value;
    var writerep = e.target.writerep.checked;
    var emailopt = e.target.emailopt.checked;

    userInfo = {
        firstname: firstname,
        lastname: lastname,
        email: email,
        country: country,
        custom-1798_0: writerep? 1 : 0,
        email_opt_in: emailopt ? 1 : 0
    };

    postUserData(userInfo, 'https://*********');
    nextSlide('.slide1');
},

rules: {
    firstname: "required",
    lastname: "required",
    country: "required",
    email: {
        required: true,
        email: true
    }
},
messages: {
    firstname: "Please enter your first name",
    lastname: "Please enter your last name",
    country: "Please select your country",
    email: {
        required: "Please enter your email address",
        email: "Please enter a valid email address"
    }
}
});

如果没有重命名最终表单上的复选框,由于CMS的限制,这是不可能的,有没有办法让这个工作?

1 个答案:

答案 0 :(得分:0)

您必须引用其中包含特殊字符或空格的属性名称。允许使用$_,但-不是,因为它也是运算符

userInfo = {
    firstname: firstname,
    lastname: lastname,
    email: email,
    country: country,
    'custom-1798_0': writerep? 1 : 0,
    email_opt_in: emailopt ? 1 : 0
};