我在WordPress上做一个项目,我在表单上的自动完成字段遇到了一些问题。控制台中未显示任何输入且没有错误。我在其中一个WordPress数据库上创建了一个小型数据库。我对AJAX不太熟悉所以请善待:)
jQuery(document).ready(function($) {
jQuery('#dish').autoComplete({
source: function(name, response) {
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: 'wp-admin/admin-ajax.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
});
这是我的jQuery代码,我在同一个文件夹中添加了admin-ajax,因为我认为它没有找到它(它是my_serach.js
)
function ajax_listings() {
global $wpdb; //get access to the WordPress database object variable
//get names of all businesse
$name = $wpdb->esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
$sql = "select name
from $wpdb->global
where name like %s
and post_type='portfolio' and post_status='publish'";
$sql = $wpdb->prepare($sql, $name);
$results = $wpdb->get_results($sql);
//copy the business titles to a simple array
$titles = array();
foreach( $results as $r )
$titles[] = addslashes($r->name );
echo json_encode($titles); //encode into JSON format and output
die(); //stop "0" from being output
我在我正在处理的主题functions.php
上添加此代码
<form method = "POST">
<div id = "container">
<div><label class="plate_label">Dish:</label><input type="text" name="dish_name[]" id="dish" class="dish" placeholder="Enter plate name" />
<label class="quantity_label">Quantity:</label><input type="text" name="dish_quantity[]" class="quantity" placeholder="Enter gram or pieces/slices" /></div>
</div>
并在表格中显示数据库中的建议。
答案 0 :(得分:0)
试试这段代码。
jQuery(document).ready(function($) {
jQuery('#dish').autoComplete({
source: function(name, response) {
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: 'http://caloriless.com/wp-admin/admin-ajax.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
});
更改ajax网址url: 'wp-admin/admin-ajax.php',
或url: 'http://caloriless.com/wp-admin/admin-ajax.php',