我有一个集成了插件的表单querybuilder.js.org
我js
的是:
从:scripts.js
$(document).ready(function(e) {
// INIT PLUGIN
$('#queryBuilder').queryBuilder({
plugins: ['bt-tooltip-errors'],
filters: [{
id: 'description',
label: 'Description',
type: 'string'
}]
});
// RESTORE RULES FROM LAST SEARCH
$('#queryBuilder').queryBuilder('setRules', decodeURIComponent($("#rules").val()) );
// ON SUBMIT, EDIT THE FORM AND APPEND SQL, PARAMS to USE IN SEARCH FROM DATABASE, AND APPEND RULES TO RESTORE IT TO NEXT LOAD OF THE PAGE
$("#btn-submit").on("click", function(e) {
e.preventDefault();
var form = $("#form");
var rules = $('#queryBuilder').queryBuilder('getRules');
var query = $('#queryBuilder').queryBuilder('getSQL', 'question_mark');
// FOR RESTORE INITIAL VALUES ON RELOAD PAGE
form.append('<input type="hidden" name="rules" value="' + encodeURIComponent(JSON.stringify(rules, null, 2)) + '">');
form.append('<input type="hidden" name="sql" value="' + query.sql + '">');
form.append('<input type="hidden" name="params" value="' + encodeURIComponent(JSON.stringify(query.params, null, 2)) + '">');
form.submit();
});
});
我的一段代码index.php
是:
<?php
if ( isset($_POST) ) {
$rules = isset($_POST['rules']) ? $_POST['rules'] : "";
}
?>
<form name="form" id="form" role="form" method="post" action="">
<div id="queryBuilder"></div>
<!--used only to restore rules in jquery-querybuilder-->
<input type="hidden" id="rules" value="<?php echo $rules; ?>">
<button type="button" id="btn-submit" class="btn btn-success">Search</button>
</form>
问题是规则没有按预期恢复。
如果我在准备好的文档上插入警报,例如:
alert(decodeURIComponent($("#rules").val()));
我得到正确的规则:
{
"condition": "AND",
"rules": [
{
"id": "description",
"field": "description",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test value"
}
],
"valid": true
}
似乎这$('#queryBuilder').queryBuilder('setRules', decodeURIComponent($("#rules").val()) );
不是初始化插件的有效方法。
如果我尝试以这种方式对规则进行硬编码:
var rules_basic = {
"condition": "AND",
"rules": [
{
"id": "description",
"field": "description",
"type": "string",
"input": "text",
"operator": "equal",
"value": "test value"
}
],
"valid": true
};
$('#queryBuilder').queryBuilder({
plugins: ['bt-tooltip-errors'],
filters: [{
id: 'description',
label: 'Description',
type: 'string'
}],
rules: rules_basic
});
然后一切正常!
如何强制从动态隐藏输入字段中获取初始化规则?我script.js
的与 HTML 是分开的,所以我不能(而且我不想)强制使用PHP
如下方式编写初始规则:
index.php
:
.... HTML PART
..... JS PART
$('#queryBuilder').queryBuilder({
plugins: ['bt-tooltip-errors'],
filters: [{
id: 'description',
label: 'Description',
type: 'string'
}],
rules: <?php echo $rules; ?> // <---------------- HERE
});