当找到数据时,可以在网页文档中显示,但如果未找到数据,则无法显示“未找到数据”的描述,并且还会出现如下错误消息:
当找不到数据时,会显示错误,并且不会显示“数据未找到”的消息,而是显示“错误”
使用 Laravel 的后端代码如下(APIController.php):
public function searchNews(Request $request)
{
$d = $request->input('q');
$news = News::where('title', 'LIKE', "%$d%")->get();
if($news->isEmpty())
{
return response()->json([
'success' => false,
'data' => 'Data Not Found',
], 404)->header('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
}
else
{
return response()->json([
'success' => true,
'data' => $news
], 200)->header('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
}
}
api.php代码如下:
Route::get('/news/v1/search', 'APINewsController@searchNews');
前端代码使用JQuery AJAX,如下(main.html):
function getNews() {
let title = $('#title').val()
$.ajax({
url: `http://127.0.0.1:8000/api/news/v1/search/?q=${title}`,
type: 'GET',
dataType: 'json',
success: function(result) {
if (result.success === true) {
$('#newsList').empty()
result.data.forEach(function(news) {
let news_data = `
<div>
<div class='card-header bg-white'>${news.title}</div>
<div class='card-body'>${news.desc}</div>
</div>
`
$('#newsList').append(news_data);
})
} else {
$('#newsList').html('<p>Data Not Found</p>')
}
},
error: function (error) {
console.log('Error:', error.responseText)
$('#newsList').html('<p>Error</p>')
}
})
}
您已经找到了解决方案,但您可以使用此 laravel 文档
更新您的回复你的新代码是
public function searchNews(Request $request)
{
$d = $request->input('q');
$news = News::where('title', 'LIKE', "%$d%")->get();
if($news->isEmpty())
{
return response([
'success' => false,
'data' => 'Data Not Found',
], 200)->header('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
}
return response([
'success' => true,
'data' => $news
], 200)->header('Access-Control-Allow-Origin', 'http://127.0.0.1:5500');
}
谢谢!