jQuery:如何AJAXify WordPress搜索?

Dim*_*zov 3 ajax wordpress search jquery

我正在尝试将AJAX功能添加到基于WordPress的站点.

当访问者单击菜单链接时,此代码会将所需页面的文本文本加载到主页面中:

$('#access a').click(function(event) {
    event.preventDefault();
    var url = $(this).attr('href');
$('#content').fadeOut(500, function() {
    $('#content').load(url, function() {
        $('#content').fadeIn(500);
        }); 
    });
});
Run Code Online (Sandbox Code Playgroud)

我的问题在于搜索表单.它在页面中具有以下结构:

<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" />
    </div>
    </form></div>
Run Code Online (Sandbox Code Playgroud)

当我键入单词测试到表单,然后单击#searchsubmit"按钮或键盘上的Enter键,我重定向到以下地址的新WordPress的页面:

http://www.myurl.com/?s=testing

这是使PHP工作的PHP代码:

<?php if ( have_posts() ) : ?>
                <h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'twentyten' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
                <?php
                /* Run the loop for the search to output the results.
                 * If you want to overload this in a child theme then include a file
                 * called loop-search.php and that will be used instead.
                 */
                 get_template_part( 'loop', 'search' );
                ?>
<?php else : ?>
                <div id="post-0" class="post no-results not-found">
                    <h2 class="entry-title"><?php _e( 'Nothing Found', 'twentyten' ); ?></h2>
                    <div class="entry-content">
                        <p><?php _e( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'twentyten' ); ?></p>
                    </div><!-- .entry-content -->
                </div><!-- #post-0 -->
<?php endif; ?>
Run Code Online (Sandbox Code Playgroud)

问题:我想阻止#searchsubmit点击和输入键点击的默认行为,并将搜索结果的内容(http://www.myurl.com/?s=whateverwordItype)加载到主要的#content中页.我怎样才能做到这一点?

(我想我只需要以某种方式在jQuery代码中插入php代码,但是这个任务有点超出了我对jQuery和PHP的了解.)

如果可能的话,我将非常感谢知识渊博的人提供的代码片段.

hit*_*uct 5

使用一些简单的jQuery和javascript

要通过ajax请求加载搜索结果,您可以使用以下代码直接从搜索结果页面获取它们:

// Bind the submit event for your form
$('#searchform').submit(function( e ){ 

    // Stop the form from submitting
    e.preventDefault();

    // Get the search term
    var term = $('#s').val();

    // Make sure the user searched for something
    if ( term ){

        $.get( '/', { s: term }, function( data ){

            // Place the fetched results inside the #content element
            $('#content').html( $(data).find('#content') );

        });

    }

});
Run Code Online (Sandbox Code Playgroud)

注意:$(data).find('#content')假设您的search.php结果聚合在一个id为content的元素中<div id="#content"> ... Results ... </div>

以上内容将进入外部文件或放在结束</body>标记之前.

您可以自定义search.php页面以组织输出结果.