我没有重力表单,但我有使用DB、csv、API等数据创建自动完成字段的经验。
这个概念保持不变,只是你呼叫和接收日期的方式有所改变,这取决于你的来源。
从我的csv开始,我寻找与地址字段含义尽可能接近的国家名称
csv结构如下
安道尔阿拉伯联合酋长国,阿富汗,等等。。。
因为我没有重力形式,也不知道它是如何工作的,所以我做了一个简单的例子,它将与输入字段一起工作,所以无论你使用什么,它都会工作
您需要使用css,因为您可能没有与我的示例中相同的容器。
我们的表单将只包含一个输入字段、输出地址和一个提交按钮
本示例重点介绍地址字段及其outcomplete功能。
<form class="gravity">
<div class="input-wrap">
<label>
<span class="label">Address:</span>
<div class="ajax-wrap">
<input type="text" name="address">
</div>
</label>
</div>
<div class="input-wrap submit">
<button type="submit">Send</button>
</div>
</form>
一些基本的css为所有内容提供结构
.gravity {
padding: 15px;
}
.gravity .input-wrap:not(:last-child) {
margin-bottom: 15px;
}
.gravity .input-wrap .ajax-wrap {
position: relative;
}
.gravity .input-wrap .ajax-wrap .address-ajax-results {
position: absolute;
top: 100%;
left: 0;
border: 1px solid #767676;
background-color: #fff;
width: 100%;
}
.gravity .input-wrap .ajax-wrap p.address-ajax-results {
padding: 10px;
font-weight: 700;
margin: 0;
}
.gravity .input-wrap .ajax-wrap ul.address-ajax-results {
max-height: 200px;
overflow-x: hidden;
overflow-y: auto;
}
.gravity .input-wrap .ajax-wrap ul.address-ajax-results li:not(:last-child) {
border-bottom: 1px solid #767676;
}
.gravity .input-wrap .ajax-wrap ul.address-ajax-results li button {
padding: 5px 10px;
display: block;
width: 100%;
text-align: left;
}
.gravity .input-wrap .ajax-wrap ul.address-ajax-results li button:hover {
background-color: #eee;
}
.gravity .input-wrap.submit button {
display: block;
background-color: #69AFE5;
color: #fff;
border-radius: 5px;
padding: 5px 10px;
width: 100%;
font-weight: 700;
}
用于请求和输出地址的客户端逻辑
($ => {
// timer for delaying ajax request for addresses
let timerBeforeCheck;
// how long to wait, in milliseconds, before the ajax request
const timerDelay = 750;
// minimum amount of charcters for a ajax request
const minChar = 2;
// our field target,
// Change it to your needs
const addressFieldTarget = \'.gravity [name="address"]\';
$(addressFieldTarget).on(\'keyup paste\', e => {
// clear previous timer
clearTimeout(timerBeforeCheck);
// the current element, address input
const $this = $(e.currentTarget);
// if minimum amount of charcters for a ajax request not met
// remove previous results and stop
if ($this.val().length < minChar) {
// clear previous results
$(\'.address-ajax-results\').remove();
return;
}
// start timer, after it finished (based on timerDelay)
// send ajax request for the csv data
timerBeforeCheck = setTimeout(() => {
// clear previous results
$(\'.address-ajax-results\').remove();
const userInput = $this.val();
$.ajax({
method: \'post\',
url: \'http://localhost/timber/wp-admin/admin-ajax.php\',
dataType: \'json\',
data: {
action: \'bt_get_form_addresses\',
address: userInput
},
success: res => {
// if no results found display message
if (!res.length) $this.after(\'<p class="address-ajax-results">No results found.</p>\');
else { // results found, build a results list a user can select from
let $list = \'\';
$list += \'<ul class="address-ajax-results">\';
res.map(address => {
$list += \'<li>\';
$list += \'<button type="button">\' + address + \'</button>\';
$list += \'</li>\';
});
$list += \'</ul>\';
$this.after($list);
}
}
});
}, timerDelay);
});
// show the addresses ajax response html input focus
// if input already has value
// that means that we already have the ajax response html
$(addressFieldTarget).on(\'click\', e => {
// prevent out global document click close from triggering
e.stopPropagation();
if ($(e.currentTarget).val().length < minChar) return;
$(\'.address-ajax-results\').show();
});
// close the ajax results on any click on page
$(document).on(\'click\', () => {
$(\'.address-ajax-results\').hide();
});
// on addresses ajax response select
// populate the address input
$(document).on(\'click\', \'.address-ajax-results button\', e => {
// prevent out global document click close from triggering
e.stopPropagation();
// populate our input
$(addressFieldTarget).val($(e.currentTarget).text());
// close ajax results
$(\'.address-ajax-results\').hide();
});
})(jQuery);
负责根据用户输入从csv文件中检索数据的服务器端逻辑
我的csv文件位于主题的根目录中,名为
countries.csv
, php代码位于
functions.php
.
要读取csv文件,我们可以这样做
fopen(__DIR__ . \'/countries.csv\', \'r\')
.
// we use this two actions in order to make our ajax request
// available for both logged and not logged in users
add_action(\'wp_ajax_bt_get_form_addresses\', \'bt_get_form_addresses\');
add_action(\'wp_ajax_nopriv_bt_get_form_addresses\', \'bt_get_form_addresses\');
function bt_get_form_addresses () {
// results to return
$found = [];
// try to open the csv
if (($handle = fopen(__DIR__ . \'/countries.csv\', \'r\')) !== FALSE) {
// sanitize and check if the user value has anything
if (!empty($address = filter_input(INPUT_POST, \'address\', FILTER_SANITIZE_STRING))) {
// start looping each csv row
while (($data = fgetcsv($handle, 1000, \',\')) !== FALSE) {
// if our csv column value doesn\'t start with X
// in this case the user value
// continue to next csv row
if (!preg_match(\'/^\' . $address . \'/i\', $data[3])) continue;
// add the found value to our results to return
$found[] = $data[3];
}
}
}
// because or ajax request expects json format
// we do the following
echo json_encode($found);
// this prevents any other code from executing
die;
}
您只需复制/粘贴代码,就可以了
只需记住创建csv文件并遵循结构即可
下面是一个关于它如何在本地环境中工作的示例。