Laravel AJAX 搜索和显示帖子

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26704650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:22:08  来源:igfitidea点击:

Laravel AJAX search and display posts

jqueryajaxsearchpostlaravel

提问by JasonK

I want to create an AJAX search with Laravel. I'm stuck at the part of displaying the results (posts) returned by the controller. So far I have this:

我想用 Laravel 创建一个 AJAX 搜索。我被困在显示控制器返回的结果(帖子)的部分。到目前为止,我有这个:

Search form (home.blade.php)

搜索表单(home.blade.php)

//The search form
{{ Form::open(array('id' => 'search', 'url' => ' ')) }}
    {{ Form::text('query', Input::old('query'), array('placeholder' => 'Search for posts..')) }}
    {{ Form::hidden('sort_col', Input::old('sort_col')) }}
    {{ Form::hidden('sort_dir', Input::old('sort_dir')) }}
    {{ Form::button('<i class="fa fa-search"></i>', array('type' => 'submit', 'name' => 'submit', 'title' => 'Zoeken')) }}
{{ Form::close() }}

Displaying the posts (home.blade.php)

显示帖子 (home.blade.php)

<!-- Posts !-->
<div id="posts">
@if (!$posts->count())
    <div class="content">No posts found!</div>
@else
    @foreach ($posts as $post)
        <div class="list-item clearfix">
            <div class="content">
                <img src="{{ URL::to($post->thumbnail) }}" alt="" />
                <h1>{{{ $post->title }}}</h1>
                <div class="tags">
                @foreach ($post->tags as $tag)
                    <abbr title="{{{ $tag->description }}}">{{{ $tag->title }}}</abbr>
                @endforeach
                </div>
            </div>
            <div class="score">
                {{ $post->rating }}
            </div>
        </div>
    @endforeach
@endif
</div>
<!-- /Posts !-->

HomeController.php

家庭控制器.php

public function postSearch()
{
    if (!Request::ajax()) {
        return null;
    }

    $input = array(
        'query'    => Input::get('query'),
        'sort_col' => Input::get('sort_col'),
        'sort_dir' => Input::get('sort_dir'),
    );

    $posts = new Post;
    $posts = $posts->select(...)->where(...)->orderBy(...); //Search query here

    Input::flash();

    return $posts;
}

The postSearch()method is being called when the search for is submitted.

postSearch()提交搜索时正在调用该方法。

The jQuery (home.blade.php)

jQuery (home.blade.php)

$('#search').submit(function(e) {
    e.preventDefault();

    var form = $(this);

    $.post(form.attr('action'), form.serialize(), function(data) {
        $('#posts').html(data);
        console.log(data);
    });
});

Everything works fine and data is being returned. It looks like this when I log the data into the console:

一切正常,正在返回数据。当我将数据记录到控制台时,它看起来像这样:

returned data in the console

控制台返回数据

The objects within the red box are the posts. How do I display those posts in the #postsdiv? I've been strugling a while now but I just can't figure it out.

红框中的对象是帖子。如何在#postsdiv 中显示这些帖子?我已经挣扎了一段时间了,但我就是想不通。

回答by lukasgeiter

You will have to loop through the array of posts and create the necessary jquery elements.
This should give you the idea:

您必须遍历帖子数组并创建必要的 jquery 元素。
这应该给你的想法:

for(var i=0; i<data.length; i++){
    var post = data[i];
    var listItem = $('<div></div>').addClass('list-item clearfix');
    var content = $('<div></div>').addClass('content');
    var img = $('<img/>').attr('src', post.thumbnail);
    var h1 = $('<h1></h1>').text(post.title);
    // etc

    content.append(img).append(h1);
    listItem.append(content);
    $('#posts').append(listItem);
}

Update

更新

For your image urls I you do something like this in your controller:

对于您的图片网址,我在您的控制器中执行以下操作:

public function postSearch()
{
    // ... code omitted

    foreach($posts as $post){
        $post->thumbnail = URL::to($post->thumbnail);
    }

    return $posts;
}

This replaces the thumbnail property with a generated full url that you can use on the client.

这将使用生成的完整 url 替换缩略图属性,您可以在客户端上使用它。