Select2组件AJAX请求404错误,无法显示结果求助
Hey there, let's tackle this 404 error with your Select2 AJAX setup step by step. The 404 means your frontend is trying to hit a URL that doesn't exist on your server, so we'll start with the most critical fixes and work through to the details.
1. Fix Route Mapping (Root Cause of 404)
First, make sure your CodeIgniter route is properly linked to your GetCountryName controller method. Open application/config/routes.php and add a clear route:
$route['get-country-names'] = 'YourActualController/GetCountryName';
Replace YourActualController with the exact name of your controller class (case sensitivity matters depending on your server/CI setup).
2. Correct Select2 AJAX Configuration
Double-check that your frontend Select2 init code uses the exact URL from your route. Here's a polished example for your #productName select:
$(document).ready(function() { $('#productName').select2({ ajax: { url: '/get-country-names', // Must match the route you defined dataType: 'json', delay: 250, // Reduce unnecessary requests data: function(params) { return { search: params.term, // Matches the 'search' parameter your controller expects page: params.page || 1 // Add pagination support (optional but recommended) }; }, processResults: function(data) { // Format server response to match Select2's required structure return { results: $.map(data, function(item) { return { id: item.id, // Adjust to your actual database column text: item.country_name // Adjust to your actual display column }; }) }; }, cache: true }, minimumInputLength: 1 // Optional: require 1+ character to trigger AJAX }); });
3. Refine Controller Method Implementation
Your controller needs to handle the search parameter, fetch valid data, and return properly formatted JSON. Here's a complete, robust example:
public function GetCountryName() { // Force JSON output to avoid CI's default HTML responses header('Content-Type: application/json'); $searchTerm = $this->input->get('search'); $page = $this->input->get('page', true, 1); $perPage = 10; // Adjust based on your needs // Fetch data from your model (replace with your actual model method) $countries = $this->country_model->search_countries($searchTerm, $page, $perPage); // Format results for Select2 $formattedResults = []; foreach ($countries as $country) { $formattedResults[] = [ 'id' => $country->id, 'text' => $country->country_name ]; } // Return JSON and stop further CI output echo json_encode($formattedResults); exit; }
Pro tip: Ensure your model's search_countries method correctly filters results using the $searchTerm and handles pagination if you're using it.
4. Debugging Steps to Confirm Fixes
- Check Network Tab: Open your browser's DevTools (F12), go to the Network tab, then trigger a Select2 search. Look for the AJAX request—if it still 404s, your URL/route mismatch is the issue.
- Test URL Directly: Paste your AJAX URL into the browser (e.g.,
http://your-domain.com/get-country-names?search=canada) to see if it returns valid JSON. If it 404s, your route or controller is misconfigured. - Verify Controller Access: Make sure your controller method is public and there's no authentication middleware blocking the request.
Common Mistakes to Avoid
- Typos in route names or AJAX URLs (case sensitivity can break requests on Linux servers)
- Forgetting to set the
Content-Type: application/jsonheader in the controller - Returning HTML (like CI error pages) instead of pure JSON
- Not matching the server response to Select2's required
idandtextfields
内容的提问来源于stack exchange,提问作者Imam Nur

