【发布时间】:2016-04-28 07:34:41
【问题描述】:
我正在尝试显示 select 2 search ajax 结果与组。但它不显示任何结果。我为此使用 WordPress Ajax。
这是我的 JS 代码,
jQuery('select.select2-group_filters-dropdown').select2({
//placeholder: "Select pages / post / categories",
ajax: {
url: ajaxurl,
dataType: 'json',
method: 'post',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page,
action: 'cp_get_posts_by_query'
};
},
results: function (data, page) {
return {results: data};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 0,
});
我从 PHP 返回的数据,
$searchString = $_POST['q'];
$childdata = array();
$query = new WP_Query( array( 's' => $searchString ) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
$title = get_the_title();
$ID = get_the_id();
$childdata[] = array('id' => "post-".$ID, 'text' => $title );
}
} else {
$data[] = array('id' => '0', 'text' => 'No results Found');
}
$data = array(
"text" => "posts",
"children" => $childdata
);
wp_reset_postdata();
// return the result in json
echo json_encode( $data );
die();
这没有按预期运行。它返回零结果。请帮我解决这个问题。
【问题讨论】:
-
尝试 print_r(json_encode( $data ));而不是回声
-
也试过了。但不工作。我的 JSON 结果是,
{"text":"posts","children":[{"id":"post-39","text":"Nihil voluptatem provident reprehenderit et voluptatem rerum"},{"id":"post-2","text":"Sample Page"},{"id":"post-99","text":"Rerum quasi odio sed"},{"id":"post-15","text":"Nesciunt iste doloribus exercitationem eligendi"},{"id":"post-104","text":"Praesentium et dolorem excepturi voluptatibus reiciendis"},{"id":"post-81","text":"Error corporis aut commodi"},{"id":"post-63","text":"Et sequi enim delectus"}]} -
您是否尝试过 console.log 收到的数据?它是在控制台上给你 0 还是什么都没有?
-
是的,我收到以下格式的对象,对象 {text: "posts", children: Array[10]}children: Array[10]0: Objectid: "post-39"text: "Nihil )} .
标签: php ajax wordpress select2