我正在尝试动态创建和加入sql查询,具体取决于哪些搜索过滤器已添加到搜索容器中。使用一个过滤器正常工作,但添加两个过滤器时,一个查询中的占位符(_ORGAN_
)不会被该过滤器元素值的值替换。
我应该如何更改search_btn函数中的代码才能使其生效?
sql = [];
query = "SELECT * FROM specimen";
$('#system').change(function () {
obj1 = {};
obj1.filter = " topography_index = '_ORGAN_'";
if ($(this).is(':checked')) {
$('#system_menu_wrapper').prependTo('#search_container');
sql.push(obj1);
}
});
$('#keyword').change(function () {
obj2 = {};
obj2.filter = " MATCH(clinical_history) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(specimen) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(macroscopic) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(microscopic) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(conclusion) AGAINST ('_KEYWORD_' IN BOOLEAN MODE) OR MATCH(comment) AGAINST ('_KEYWORD_' IN BOOLEAN MODE)";
if ($(this).is(':checked')) {
$('#keyword_field_wrapper').prependTo('#search_container');
sql.push(obj2);
}
});
$('#search_container').on('click', '#search_btn', function () {
if ($("#search_container").find('#system_menu_wrapper').length) {
var regExp1 = new RegExp('_ORGAN_', 'g');
$.each(sql, function (index, value) {
// store the replacement string as the .replaced property
// so the .filter property remains unchanged and can be used
// again in the future
sql[index].replaced = sql[index].filter.replace(regExp1, 'T' + $('#organ_menu').val());
});
};
if ($("#search_container").find('#keyword_field_wrapper').length) {
var regExp2 = new RegExp('_KEYWORD_', 'g');
$.each(sql, function (index, value) {
// store the replacement string as the .replaced property
// so the .filter property remains unchanged and can be used
// again in the future
sql[index].replaced = sql[index].filter.replace(regExp2, $('#keyword_field').val());
});
}
if (sql.length) {
var q = $.map(sql, function (elem) {
return elem.replaced;
});
query += " WHERE " + q.join(' AND ');
}
$.ajax({
type: "POST",
url: 'scripts/do_search.php',
data: {
query: query,
},
success: function (data) {
$('#search_results').html(data);
$('#search_results').show();
query = "SELECT * FROM specimen";
}
});
});
答案 0 :(得分:1)
将第二个字段的处理更改为:
if ($("#search_container").find('#keyword_field_wrapper').length) {
var regExp2 = new RegExp('_KEYWORD_', 'g');
var replacement = $('#keyword_field').val();
$.each(sql, function (index, value) {
// store the replacement string as the .replaced property
// so the .filter property remains unchanged and can be used
// again in the future
value.replaced = (value.replaced || value.filter).replace(regExp2, replacement);
});
}
如果它存在,则使用replaced
属性作为输入,否则使用filter
属性,以便它构建在第一个循环的替换上。
另外,请注意,您可以使用迭代函数的value
参数,而不是每次都必须访问sql[index]
。由于$('#keyword_field').val()
在循环期间不会发生变化,因此应将其缓存在循环外的变量中。