在这里发布之前,我倾向于做很多研究。但是,这次我找不到任何原因导致以下代码无法按预期工作。
我有一个实现以下代码的Wordpress主题:
jQuery(document).ready(function() {
jQuery( "#title" ).autocomplete({
/* source : JSON.parse('[{"label":"HAPPY","value":"HAPPY"},{"label":"HAPPY BIRTHDAY DETECTIVE","value":"HAPPY BIRTHDAY DETECTIVE"},{"label":"HAPPY BIRTHDAY HOLLYWOOD","value":"HAPPY BIRTHDAY HOLLYWOOD"},{"label":"HAPPY BIRTHDAY TO ME","value":"HAPPY BIRTHDAY TO ME"},{"label":"HAPPY DAYS","value":"HAPPY DAYS"},{"label":"HAPPY DAYS ","value":"HAPPY DAYS "},{"label":"HAPPY DAYS ","value":"HAPPY DAYS "},{"label":"HAPPY DAYS ","value":"HAPPY DAYS "},{"label":"HAPPY END","value":"HAPPY END"},{"label":"HAPPY ENDING","value":"HAPPY ENDING"},{"label":"HAPPY EVER AFTERS","value":"HAPPY EVER AFTERS"},{"label":"HAPPY EVER AFTERS","value":"HAPPY EVER AFTERS"},{"label":"HAPPY FAMILY","value":"HAPPY FAMILY"},{"label":"HAPPY FAMILY","value":"HAPPY FAMILY"},{"label":"HAPPY FAMILY","value":"HAPPY FAMILY"},{"label":"HAPPY GILMOUR","value":"HAPPY GILMOUR"},{"label":"HAPPY HOUR","value":"HAPPY HOUR"},{"label":"HAPPY HOUR","value":"HAPPY HOUR"},{"label":"HAPPY MAGIC","value":"HAPPY MAGIC"},{"label":"HAPPY TANK YOU MORE PLEASE","value":"HAPPY TANK YOU MORE PLEASE"},{"label":"HAPPY TANK YOU MORE PLEASE","value":"HAPPY TANK YOU MORE PLEASE"},{"label":"HAPPY TANK YOU MORE PLEASE","value":"HAPPY TANK YOU MORE PLEASE"},{"label":"HAPPY TANK YOU MORE PLEASE","value":"HAPPY TANK YOU MORE PLEASE"},{"label":"HAPPY TOGETHER","value":"HAPPY TOGETHER"},{"label":"HAPPY TOGETHER","value":"HAPPY TOGETHER"}]'), */
minChars: 3,
source: function(request,response) {
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: '/wordpress/wp-admin/admin-ajax.php',
data: 'action=get_listing_names&name='+jQuery("#title").val(),
success: function (data) {
console.log(data);
},
error: function(e) {
console.log(e);
},
});
}
});
});
在主题的functions.php文件中,注册了正确的功能后,我写了这样的内容:
function ajax_listings() {
global $wpdb; //get access to the WordPress database object variable
$return_arr = array();
//get names of all businesses
$q = $wpdb->esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
$mydb = new wpdb('xxx','xxx','xxxx','xxxx');
$rows = $mydb->get_results("select id,title from table1 where title like '".$q."%' order by title asc");
foreach( $rows as $row) {
$row_array['label'] = $row->title;
$row_array['value'] = $row->title;
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
die();
}
一切都很好。我可以看到,在Chrome浏览器中,我得到了PHP的回显(在该Ajax调用的预览选项卡中)和成功进行Ajax调用时的数据。数据是正确的JSON编码,正如我通过在控制台中查看颜色以及成功回调函数中的答案How to check if a string is a valid JSON string in JavaScript without using Try/Catch测试的那样。
但是,结果只是不显示。有趣的是,我复制并粘贴了从PHP获得的字符串(通过暂时排除json_encode)并对其进行了硬编码(您可能会看到数据集被注释为源),并且一切正常。
所以,我真的不知道为什么从PHP发送数据集时为什么不显示结果,但是如果我复制并粘贴相同的数据集(作为字符串)并在Javascript中解析为JSON,则为什么不显示结果。 / p>
一种解决方法可能是要求PHP返回一个字符串,然后使用Javascript对其进行解析,但是由于自动完成功能似乎无法提供这种可能性,因此我不知道如何处理这种情况。
谢谢! 法比奥