含连字符的Checkbox提交JSON数据失败的解决方案咨询
解决带连字符的表单字段JSON解析问题
Got it, let's fix this issue right up! The problem here is straightforward: when you use a key with a hyphen (like custom-1798_0) directly in a JavaScript object literal without quotes, the interpreter treats the hyphen as a subtraction operator—causing a syntax error that breaks JSON serialization. Since you can't change the CMS-generated field name, here are two simple, working fixes:
方法1:用引号包裹带特殊字符的键名
修改你的userInfo对象定义,把带连字符的键名用双引号(或单引号)括起来,这样JavaScript就会把它识别为完整的键名:
userInfo = { firstname: firstname, lastname: lastname, email: email, country: country, "custom-1798_0": writerep? 1 : 0, // 用引号包裹带连字符的键 email_opt_in: emailopt ? 1 : 0 };
方法2:使用括号语法赋值
先创建空对象,再通过括号语法添加带连字符的键,这种方式同样能避开语法问题:
var userInfo = {}; userInfo.firstname = firstname; userInfo.lastname = lastname; userInfo.email = email; userInfo.country = country; userInfo["custom-1798_0"] = writerep ? 1 : 0; // 括号语法处理特殊键名 userInfo.email_opt_in = emailopt ? 1 : 0;
两种方法都能让userInfo对象正确包含custom-1798_0这个键,后续postUserData在序列化对象为JSON时,也能正常解析这个带连字符的键名,完全不需要修改CMS生成的表单字段。
内容的提问来源于stack exchange,提问作者Georgia O'Brien
相关产品推荐
相关产品推荐

