{{$catego-6ren">
gpt4 book ai didi

php - 如何使用append方法在#posts div中显示属于点击类别的帖子?

转载 作者:行者123 更新时间:2023-12-01 08:39:06 26 4
gpt4 key购买 nike

我有一个包含一些帖子类别的菜单:

<ul>
@foreach($categories->get() as $category)
<li class="ative">
<a href="#" name="category" id="{{$category->id}}">{{$category->name}}</a>
</li>
@endforeach
</ul>

当我单击类别(例如 ID“1”)时,通过菜单我想在“#posts”div 中显示属于 ID“1”类别的帖子。

因此,#posts div 在第一次访问页面时显示最后的帖子,但在单击类别后,它应该显示属于单击的类别的帖子。所以我有#posts div:

<div id="posts">
@foreach($posts as $post)
<div id="posts">
<img src="{{$post->image}}">
<h1>{{$post->title}}</h1>
<!-- ... -->
</div>
@endforeach
</div>

如果在控制台中单击 ID 为“1”的类别,则会显示该 ID 为“1”的类别目前存在的唯一帖子的信息:

{id: 1, title: "Title", description: "", …}

现在你知道如何使用append方法在#posts div中显示属于点击类别的帖子了吗?类似下面的东西(但像下面这样不起作用):

$('#posts').append(
<div id="posts">
<img src="{{$post->image}}">
<h1>{{$post->title}}</h1>
</div>);
});

我有一个显示主页的 FrontController 索引方法:

public function index(){
return view('home')
->with('categories', Category::orderBy('created_at', 'desc')->get())
->with('posts', Post::orderBy('created_at','desc')->get());
}

我还有一个 PostController,它有一个 postsFromCategory 方法来从选定的类别中获取帖子:

 public function WhereHasCategory(Request $request)
{
$posts = Post::whereHas('categories', function ($categories) use (&$request) {
$categories->where('category_post.id',$request->id);
})->get();
return response()->json($posts);
}

然后在index.blade.php中我有ajax:

$.ajax({
url: '{{ route('category.posts',null) }}/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
$.each(result,function(index, post){
//$('#posts').append(<span>post.title</span>);
});
console.log(result);
},
error: function(error) {
console.log(error.status)
}
});

最佳答案

尝试更改此行,我不知道这是否是一个拼写错误,但您需要发送一个字符串到附加函数,然后使用来自 javascript 的变量而不是来自 php 的变量。

//$('#posts').append(<span>post.title</span>);

至:

$('#posts').append('<div id="posts">' +
'<img src="'+ post.image +'">' +
'<h1>'+ post.title +'</h1>' +
'</div>');

关于php - 如何使用append方法在#posts div中显示属于点击类别的帖子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49577868/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com