jQuery get请求未检索HTML [英] jQuery get request not retrieving HTML
问题描述
我正在尝试使用$.get()
请求来检索一些HTML数据,这些数据将在PHP文件中返回.
I'm trying to use a $.get()
request to retrieve some HTML data which is returned inside a PHP file.
jQuery:
$.get( "/invite/all", function( return_data ) {
console.log(return_data);
});
PHP:
public function getInvites()
{
$invites = DB::table('invites')->where('user_to', '=', 2)->get();
if(!empty($invites)) {
ob_start();
foreach ($invites as $invite):
$invite_channel = DB::table('channels')->where('channel_id', '=', $invite->channel)->first();
?>
<tr>
<td><?php echo $invite_channel->channel_name; ?></td>
<td>
<button>Action</button>
</td>
</tr>
<?php
endforeach;
return response()->json([
'success' => true,
'empty' => false,
'message' => ob_get_clean()
]);
} else {
return response()->json([
'success' => true,
'empty' => true,
'message' => 'You currently have no invites'
]);
}
}
使用Postman时,它会按预期返回数据,但是当我在网页上使用它时,它会显示JSON,但message
字段为空.
When using Postman it returns the data as expected, but when I'm using this on a webpage, it shows the JSON but the message
field is empty.
推荐答案
您可以通过将html移至刀片模板来清除该问题.另外,如果您使用过雄辩的关系,也可以轻松解决一点点问题.
You could clean that up by moving the html to a blade template. Also if you used eloquent relationships that could get cleaned up a lil bit easier as well.
如何显示东西实际上并不是控制器的关注点.我们拥有用于处理该视图的整个View层.它只需要处理请求并返回某种类型的响应即可.让视图层处理标记的细节.
How stuff is displayed shouldn't be a concern of the controller in reality. We have the entire View layer for handling that. It just need to handle the request and return some type of response. Let the view layer handle the specifics of the markup.
public function getInvites()
{
$invites = Invite::with('channel')->where('user_to', 2)->get();
return response()->json([
'success' => 'true',
'empty' => $invites->isEmpty(),
'message' => $invites->isEmpty()
? 'You currently have no invites'
: view('partial.invites', ['invites' => $invites])->render(),
]);
}
// resources/views/partial/invites.blade.php
@foreach ($invites as $invite)
<tr>
<td>{{ $invite->channel->channel_name }}</td>
<td>
<button>Action</button>
</td>
</tr>
@endforeach
这篇关于jQuery get请求未检索HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!