【发布时间】:2018-11-20 17:50:14
【问题描述】:
我正在尝试让 JQuery 自动完成脚本在 Wordpress 中工作。我相信我已经正确设置了所有内容,因为当我在输入字段中输入数据时确实出现错误,但随后出现以下错误。所以,我认为 JSON 有问题,但我不确定如何调试它。
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Function.n.parseJSON (jquery.js?ver=1.12.4:4)
at Function.a.parseJSON (jquery-migrate.min.js?ver=1.4.1:2)
at Object._transformResult [as transformResult] (jquery.autocomplete.js?ver=4.9.8:133)
at Object.<anonymous> (jquery.autocomplete.js?ver=4.9.8:584)
at i (jquery.js?ver=1.12.4:2)
at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4:2)
at y (jquery.js?ver=1.12.4:4)
at XMLHttpRequest.c (jquery.js?ver=1.12.4:4)
这是返回的 JSON:
["Hello world!","Email Notification","Email Notification","Formidable Style","Email Notification","Email Notification","Email Notification","Chapter Maintenance - Admin View","Chapter Info - All","Featured Members"]
从我看过的其他帖子中,评论是它没有被正确解析,但我无法从我的研究中确定如何解决这个问题。
这里是 Jquery:
jQuery(document).ready(function($) {
$('#autocomplete-id').autocomplete({
source: function(name, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wp-admin/admin-ajax.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
});
这是我用来通过 admin-ajax.php 返回 JSON 的 Wordpress 的 functions.php 中的函数
add_action('wp_ajax_nopriv_get_listing_names', 'ajax_listings');
add_action('wp_ajax_get_listing_names', 'ajax_listings');
function ajax_listings() {
global $wpdb; //get access to the WordPress database object variable
//get names of all businesses
$name = $wpdb->esc_like(stripslashes($_POST['name'])).'%'; //escape for use in LIKE statement
$sql = "select post_title
from $wpdb->posts
where post_status='publish' LIMIT 10";
$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->post_title);
echo json_encode($titles); //encode into JSON format and output
die(); //stop "0" from being output
}
我尝试将 console.log(data) 输入成功区域,但我得到的只是没有任何数据的错误。
当我查看“网络”选项卡时,我会看到当我在输入框中输入字母时的请求,但它们显示的只是 ?query=a 或 ?query=b。
如果我单击其中一个,它会加载我当前所在的页面(带有自动完成输入框),并在其末尾添加 ?query=a,因此看起来不正确。
我只是不确定为什么,如果正确设置以从 admin-ajax.php 获取数据。
我的主要问题是,我该怎么做才能进一步调试?
【问题讨论】:
-
'/wp-admin/admin-ajax.php'返回 HTML 而不是 JSON -
在“网络”选项卡中,查看“响应”选项卡以查看
/wp-admin/admin-ajax.php?action=get_listing_names&name=name返回的内容。 -
不是问题,而是向你传递这样的数据
data: {action: get_listing_names, name: name}, -
@aynber。嗯,实际上,admin-ajax.php 中没有任何内容。
-
@Andreas 我将结果编码为 JSON。你是说你不能从 admin-ajax.php 回显 JSON 吗?我认为这是在 Wordpress 中使用 ajax 的唯一可接受的方式?我在这里错过了什么吗?
标签: php jquery json ajax wordpress