我正在为wordpress构建ajax搜索插件。当我想将结果转换为json时,我没有输出。当然,我的插件可以在没有Json转换的情况下工作。
(如果我不使用Json,可以吗??)
我的代码是:
search\\u表单。php:
add_action( \'wp_ajax_nopriv_ajax_search2\', \'ajax_search2\' );
function ajax_search2() {
$data = array();
$val =$_POST[\'val\'];
echo $val;
if(strlen($val) > 3){
$ppp = 6;
$post_type = \'product\';
$args = array(
\'s\' => $val,
\'post_type\' => $post_type,
\'posts_per_page\' => $ppp
);
$query = new WP_Query($args);
if($query->have_posts()){
while($query->have_posts()){
$query->the_post();
$link=get_permalink( get_the_ID() );
$thumb = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),\'thumbnail\');
$thumb = $thumb[0];
$data[\'product\'] .= \'<li><img src="\'.$thumb.\'"><span><a href="\'.$link.\'">\'.$query->post->post_title.\'</a></span></li>\';
}
if($query->found_posts > 6){
$data[\'product\'] .= \'<li class="more"><a href="\'.site_url().\'/?s=\'.$val.\'&post_type=\'.$post_type.\'">ادامه</a></li>\';
// \'the post font after 6\';
}
wp_reset_postdata();
}else{
$data[\'product\'] = "no product found2";
}
}
$result = wp_json_encode($data);
wp_send_json($result);//
}
ajax。js公司:
jQuery(document).ready(function ($) {
//alert(\'this is a test for ajax\');
$(window).click(function(){
$(\'.box-search\').css(\'opacity\',\'0\');
})
$(\'.box-search\').click(function(event){
event.stopPropagation();
})
var SearchReq = null;
$(\'.search .search-field\').keyup(function(){
$(\'.box-search\').css(\'opacity\',\'1\');
var val = $(\'.search .search-field\').val();
ajaxSearch(val);
})
function ajaxSearch(val){
if( val.length < 3){
$(\'.box-search\').css(\'opacity\',\'0\');
return;
}
SearchReq = $.ajax({
type: \'POST\',
dataType : "json",
url:\'http://ferfri.ir/wp-admin/admin-ajax.php\',
data:{
action : \'ajax_search2\',
val : val
},beforeSend:function(){
$(\'.box-search ul\').html(\'قبل از ارسال\');
if(SearchReq != null){
SearchReq.abort();
}
},success:function(res){
res = JSON.parse(res);
$(\'.box-search ul.product\').html(res.product);
$(\'.box-search ul.news\').html(res);
}
})
}
});