如何从Laravel控制器输出JavaScript Alert?报错问题解决
Hey there! Let's break down why you're hitting that "Unexpected token < in JSON at position 0" error and fix it properly.
The Root Cause
That error pops up because your Laravel controller is likely returning a JSON-formatted response (either via response()->json() or returning an array directly), but you're outputting raw <script> HTML/JS content. When the frontend (especially AJAX requests) tries to parse the response as JSON, it hits the < character first— which isn't valid JSON syntax— hence the parsing failure.
Fixes to Try
Here are the most practical ways to get that alert working without breaking your response format:
1. Return a View with the Script (Best for Non-AJAX Scenarios)
If your controller is meant to render a full page, don't output the script directly from the controller. Instead, create a Blade view and return it:
// Your Controller Method public function showAlert() { return view('alert-page'); }
Then create resources/views/alert-page.blade.php with your script:
<!DOCTYPE html> <html> <body> <script type="text/javascript">alert("hello!");</script> </body> </html>
2. Use Session Flash Messages (Great for AJAX or Redirects)
For AJAX requests or post-redirect scenarios, store your alert message in the session and trigger the alert from your frontend Blade template:
// Controller Code public function triggerAlert() { // Store the message temporarily in the session session()->flash('alert_message', 'hello!'); // For AJAX requests: return JSON to tell the frontend to show the alert if (request()->ajax()) { return response()->json(['show_alert' => true, 'message' => 'hello!']); } // For non-AJAX: redirect back to the previous page return redirect()->back(); }
Add this to your main layout file (e.g., layouts/app.blade.php) to auto-render alerts from the session:
@if(session('alert_message')) <script>alert("{{ session('alert_message') }}");</script> @endif
If using AJAX, handle the response in your frontend JS:
// Example with Axios axios.post('/your-endpoint').then(response => { if (response.data.show_alert) { alert(response.data.message); } });
3. Return an HTML Response (If You Must Output Script Directly)
If you absolutely need to send the script straight from the controller, force the response to use text/html content-type so the frontend doesn't try to parse it as JSON:
public function sendAlertScript() { return response('<script type="text/javascript">alert("hello!");</script>', 200) ->header('Content-Type', 'text/html'); }
Pro Tip
Avoid outputting raw HTML/JS directly from controllers—it's not a clean Laravel practice and makes your code harder to maintain. Stick to views or session flash messages whenever possible.
内容的提问来源于stack exchange,提问作者Dharmik Unagar

