我使用 BootstrapValidator 作为我的验证组件。我需要将从 PHP 收集到的选项提供给其构造函数,如下所示:
生成字段的 PHP 代码:
$fields = "";
foreach ($form["questions"] as $key => $value) {
if (!empty($value["validators"])) {
$fields .= "\"" . $key . "\":" . json_encode($value["validators"]) . ",";
}
}
$new_fields = "{" . chop($fields, ",") . "}";
Javascript部分是:
$('#my_form').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: <?php echo $new_fields; ?>
});
它打印出类似的内容:
$('#fc_register_form').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
"field_1": {"notEmpty": {"message": "The ****** cannot be empty"}},
"field_1_confirm": {
"notEmpty": {"message": "The ******* must be same with first input for ******."},
"identical": {
"field": "field_1",
"message": "The given value is not same with first input for ****"}
},
"field_2": {"notEmpty": {"message": "The ******* empty"}},
"field_3": {"notEmpty": {"message": "The ******* empty"}},
"field_4": {"notEmpty": {"message": "The ****** is required and cannot be left empty"}}
}
});
那么,双引号可能会导致它不起作用吗?或者说这有什么问题吗?但我想应该不会那么多......
最佳答案
我刚刚意识到我的评论并不完整。
PHP 代码
$fields = array();
foreach ($form["questions"] as $key => $value) {
if (!empty($value["validators"])) {
$fields[$key] = $value["validators"];
}
}
JavaScript 代码
$('#my_form').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: <?php echo json_encode($fields); ?>
});
关于javascript - 如何将选项从 PHP 传递到 Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26723799/