Laravel 以 json 格式显示/返回数据,而不是以 html 格式显示/返回数据
Posted
技术标签:
【中文标题】Laravel 以 json 格式显示/返回数据,而不是以 html 格式显示/返回数据【英文标题】:Laravel Displaying/returning data in json format instead of displaying/returning data in html format 【发布时间】:2019-08-11 16:33:54 【问题描述】:我有一种奇怪的情况,数据以 json 格式而不是 html 格式显示! 在路由http://127.0.0.1:8000/addpost 显示添加帖子的表单和最近添加的帖子。
它显示要添加帖子的表单,当点击提交时,它会以 json 格式返回数据,而不是显示表单和添加的帖子。 1)为什么它返回 json 数据? 2)如何以html格式显示数据? 这就是我的路线
web.php
Route::get('addpost','PostController@index');
Route::post('addpost','PostController@store');
控制器->
PostController.php
class PostController extends Controller
public function index()
$posts = Post::latest()->first();
return view('addpost',compact('posts'));
public function store(Request $request)
$post =new Post();
$post->title= $request->input('title');
$post->body= $request->input('body');
if($request->hasfile('postimage'))
$file=$request->file('postimage');
$extention=$file->getClientOriginalExtension();
$filename=time().'.'.$extention;
$file->move('uploads/post',$filename);
$post->postimage=$filename;
else
return $request;
$post->postimage='';
$post->save();
return back()->with('success', 'Your images has been successfully Upload');
和视图
<div class="container">
<div class="jumbotron">
@if(Auth::user())
<h3> Add new post with images</h3>
<form action="url('addpost')" method="POST" enctype="multipart/form-data">
csrf_field()
<div class="form-group">
<label>Title</label>
<input type="text" name="title" class="form-control" >
</div>
<div class="form-group">
<label>Body</label>
<input type="text" name="body" class="form-control" >
</div>
<div class="input-group">
<div class="custom-file">
<input type="file" name="image" class="custom-file-input">
<label class="custom-file-label">Choose file</label>
</div>
</div>
<button type="submit" name="submit" class="btn-brn-primary"> Save Post</button>
@if($posts)
@foreach($posts as $post)
<tr>
<td>$post->id</td>
<td>$post->title</td>
<td>$post->body</td>
<!-- <td><img src="asset('uploads/post/'.$post->image)" style="height: 150px;"></td>
<td><a href="">EDIT</a></td> -->
</tr>
@endforeach
@endif
@else
<h1>no</h1>
@endif
</form>
</div>
</div>
【问题讨论】:
【参考方案1】:if($request->hasfile('postimage')) // -> you are checking for postimage, in your html
// markup the file filed is called "image",
// therefore you will never enter this if block
$file=$request->file('postimage');
$extention=$file->getClientOriginalExtension();
$filename=time().'.'.$extention;
$file->move('uploads/post',$filename);
$post->postimage=$filename;
else
return $request; // here you are returning the $request object that
// causes your unformatted response
$post->postimage='';
【讨论】:
以上是关于Laravel 以 json 格式显示/返回数据,而不是以 html 格式显示/返回数据的主要内容,如果未能解决你的问题,请参考以下文章