jQuery:如何AJAXify WordPress搜索?

我正在尝试将 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);
        }); 
    });
});

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

<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>

当我在表单中键入单词测试,然后单击键盘上的#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; ?>

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

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

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

解决方法

使用一些简单的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') );

        });

    }

});

注意:$(data).find(‘#content’)假设您的search.PHP结果聚合在一个id为content的元素中,即< div id =“#content”> ……结果……< / div>

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

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

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...