如何在PHP中通过AJAX向Test控制器的Store方法插入数据?
Alright, let's walk through how to complete this AJAX-powered data insertion for your Laravel setup (I'm making an educated guess here since your code uses Laravel's Request class and model syntax). Here's a step-by-step, practical breakdown:
store Method First, let's polish your existing controller code to handle file uploads (since you have an image field) and return proper JSON responses for AJAX:
use Illuminate\Http\Request; use App\Models\books; // Ensure your model path is correct use Illuminate\Support\Facades\Storage; public function store(Request $request) { // Validate incoming request data $validated = $this->validate( $request, [ 'name'=>'required|string|unique:books,book_name|max:30', 'writer'=>'required|string|max:30', 'publisher_name'=>'required|string|max:30', 'publisher_date'=>'required|date', // Added date validation for sanity 'description'=>'required|string', 'pages_num'=>'required|integer|between:1,5000', 'image'=>'required|image|mimes:jpeg,png,jpg,gif|max:2048' // Add image-specific rules ] ); // Create a new books instance $book = new books; $book->book_name = $request->input('name'); $book->writer = $request->input('writer'); $book->publisher_name = $request->input('publisher_name'); $book->publisher_date = $request->input('publisher_date'); $book->description = $request->input('description'); $book->pages_num = $request->input('pages_num'); // Handle image upload if ($request->hasFile('image')) { $imagePath = $request->file('image')->store('book_images', 'public'); // Store in storage/app/public/book_images $book->image = $imagePath; // Save the path to the database } // Save the book to the database $book->save(); // Return success response for AJAX return response()->json([ 'success' => true, 'message' => 'Book added successfully!', 'data' => $book ]); }
A couple quick notes here:
- I added image validation rules to ensure only valid image files are uploaded
- Switched from
Input::get()to$request->input()(the modern, recommended Laravel approach) - Added storage logic for the image using Laravel's
Storagefacade - Returned a JSON response so your frontend AJAX can easily parse the result
Create an HTML form with enctype="multipart/form-data" (critical for file uploads) and include Laravel's CSRF token for security:
<form id="bookForm" enctype="multipart/form-data"> @csrf <!-- Laravel CSRF protection --> <div> <label for="name">Book Name:</label> <input type="text" id="name" name="name" required> </div> <div> <label for="writer">Writer:</label> <input type="text" id="writer" name="writer" required> </div> <div> <label for="publisher_name">Publisher:</label> <input type="text" id="publisher_name" name="publisher_name" required> </div> <div> <label for="publisher_date">Publish Date:</label> <input type="date" id="publisher_date" name="publisher_date" required> </div> <div> <label for="description">Description:</label> <textarea id="description" name="description" required></textarea> </div> <div> <label for="pages_num">Number of Pages:</label> <input type="number" id="pages_num" name="pages_num" min="1" max="5000" required> </div> <div> <label for="image">Book Cover:</label> <input type="file" id="image" name="image" accept="image/*" required> </div> <button type="submit">Add Book</button> </form> <!-- Optional: For displaying success/error messages --> <div id="responseMessage"></div>
You can use either vanilla JavaScript or jQuery. Let's cover both options:
Option 1: jQuery (Simpler for FormData)
$(document).ready(function() { $('#bookForm').on('submit', function(e) { e.preventDefault(); // Prevent default form submission let formData = new FormData(this); // Capture all form data including file $.ajax({ url: "{{ route('test.store') }}", // Use Laravel route helper type: 'POST', data: formData, contentType: false, // Required for FormData processData: false, // Required for FormData success: function(response) { // Handle success $('#responseMessage').html('<p style="color: green;">' + response.message + '</p>'); $('#bookForm')[0].reset(); // Reset the form }, error: function(xhr) { // Handle validation errors or server issues let errors = xhr.responseJSON.errors; let errorHtml = '<ul style="color: red;">'; $.each(errors, function(key, value) { errorHtml += '<li>' + value[0] + '</li>'; }); errorHtml += '</ul>'; $('#responseMessage').html(errorHtml); } }); }); });
Option 2: Vanilla JavaScript
document.addEventListener('DOMContentLoaded', function() { const form = document.getElementById('bookForm'); const responseMessage = document.getElementById('responseMessage'); form.addEventListener('submit', function(e) { e.preventDefault(); const formData = new FormData(this); fetch("{{ route('test.store') }}", { method: 'POST', body: formData, headers: { 'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content // Note: We don't set Content-Type here - browser handles it for FormData } }) .then(response => response.json()) .then(data => { if (data.success) { responseMessage.innerHTML = `<p style="color: green;">${data.message}</p>`; form.reset(); } }) .catch(error => { console.error('Error:', error); responseMessage.innerHTML = '<p style="color: red;">Something went wrong. Please try again.</p>'; }); }); });
Add this to your routes/web.php file to map the request to your controller:
use App\Http\Controllers\TestController; // Ensure your controller path is correct Route::post('/test/store', [TestController::class, 'store'])->name('test.store');
- Make sure your
booksmodel has fillable attributes set (otherwise mass assignment will fail):class books extends Model { protected $fillable = ['book_name', 'writer', 'publisher_name', 'publisher_date', 'description', 'pages_num', 'image']; } - If you're using Laravel's storage, run
php artisan storage:linkto make the uploaded images accessible via the web.
内容的提问来源于stack exchange,提问作者Hala Skhaya

