jQuery获取请求不检索HTML
我正在尝试使用$.get()
请求来检索在PHP文件中返回的一些HTML数据。
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(); ?> channel_name; ?> 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
字段为空。
你可以通过将html移动到刀片模板来清理它。 此外,如果您使用雄辩的关系,可以更容易清理一点点。
显示的东西不应该是控制器实际关注的问题。 我们有整个View层来处理它。 它只需要处理请求并返回某种类型的响应。 让视图层处理标记的细节。
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) {{ $invite->channel->channel_name }} @endforeach
不要使用ob_start()和ob_get_clean()。 将HTML代码保存在变量中,然后将其添加到响应中。
$html = ''; foreach ($invites as $invite) { $html += ''; $html += '' . $invite_channel->channel_name . ' '; $html += ''; $html += ''; $html += ' '; $html += ' '; } return response()->json([ 'success' => true, 'empty' => false, 'message' => $html ]);