9

我需要设置 wordpress ajax 搜索结果,但我的方法在单击按钮时没有检索结果,而是将我重定向到另一个站点( myurl.com?s=term )。我正确调用了 admin-ajax.php,但设置不正确。任何想法是什么导致了问题?

//Script to activate ajax
 jQuery(document).ready(function($){
  var search_val=$("#s").val();
  $('#searchsubmit').click(function(){
    $.post(
        WPaAjax.ajaxurl,
        {
            action : 'wpa56343_search',
            search_val : search_val
        },
        function( response ) {
            $('#results').append( response );
        }
    );
   });

 });

//function to setup wp_query
add_action('wp_ajax_wpa56343_search', 'wpa56343_search');
function wpa56343_search(){
  global $wp_query;
  $search = $_POST['search_val'];
  $args = array(
    's' => $search,
    'posts_per_page' => 5
  );
  $wp_query = new WP_Query( $args );

  get_template_part( 'search-results' );

  exit;
}

//html

  <div id="my_search">
   <form role="search" method="get" id="searchform" action="http://myurl.com/" >
    <input type="text" value="" name="s" id="s" />
    <input type="submit" id="searchsubmit" value="Search" />
   </form>
  </div>
  <div id="results"></div>  
4

2 回答 2

13

您应该将代码包装在document.ready

$(document).ready(function(){
    $("#searchsubmit").click(function(e){
        e.preventDefault();
        var search_val=$("#s").val(); 
        $.post(search.php,{search_string:search_val},function(data){
            if(data.length>0){
                $("#results").html(data);
            }
        });
    });   
});

更新:

$(document).ready(function(){
    $("#searchsubmit").click(function(e){
        e.preventDefault();
        var search_val=$("#s").val(); 
        $.ajax({
            type:"POST",
            url: "./wp-admin/admin-ajax.php",
            data: {
                action:'wpa56343_search', 
                search_string:search_val
            },
            success:function(response){
                $('#results').append(response);
            }
        });
    });   
});

在你的functions.php中

add_action('wp_ajax_nopriv_wpa56343_search', 'wpa56343_search'); // for not logged in users
add_action('wp_ajax_wpa56343_search', 'wpa56343_search');
function wpa56343_search()
{
    // code
}
于 2012-06-23T22:41:13.797 回答
1

您也可以使用 typeahead.js jquery 插件,阅读此完整教程以获取更多信息:

http://wp.tutsplus.com/tutorials/plugins/enhancing-the-search-form-with-typeahead-js/

于 2013-10-17T17:40:06.437 回答