如何保护在线考试系统中Codeigniter返回的JSON响应?
Hey there! Let's walk through implementing the question fetching workflow for your CodeIgniter-based online exam web app—here's how to tie together the backend query and frontend AJAX call smoothly.
CodeIgniter Backend: Fetch & Return Questions via JSON
First, let's set up the controller and model to handle the GET request and query your questions table.
Controller Method (e.g., Exam.php)
This method will accept optional filter parameters, query the database, and send back a JSON response:
public function get_questions() { // Grab optional GET parameters (adjust based on your table structure) $subject_id = $this->input->get('subject_id'); $difficulty = $this->input->get('difficulty'); // Load your questions model $this->load->model('Question_model'); $questions = $this->Question_model->fetch_questions($subject_id, $difficulty); // Handle empty result set if (empty($questions)) { $this->output ->set_status_header(404) ->set_content_type('application/json') ->set_output(json_encode(['error' => 'No matching questions found'])); return; } // Return valid JSON response $this->output ->set_content_type('application/json') ->set_output(json_encode($questions)); }
Model Method (e.g., Question_model.php)
This handles the actual database query, with optional filters:
public function fetch_questions($subject_id = null, $difficulty = null) { $this->db->select('*'); $this->db->from('questions'); // Replace with your actual table name // Apply filters if parameters are provided if ($subject_id) { $this->db->where('subject_id', $subject_id); } if ($difficulty) { $this->db->where('difficulty', $difficulty); } return $this->db->get()->result_array(); }
Frontend: AJAX GET Request to Fetch Questions
Here's the completed getQuestions() function using jQuery, plus a helper function to render questions on the page:
function getQuestions() { // Define any filters you want to send (e.g., subject ID from a dropdown) const queryParams = { subject_id: $('#subject-select').val(), // Dynamic value from UI difficulty: 'medium' // Example static value, adjust as needed }; $.ajax({ url: '/exam/get_questions', // Match your CodeIgniter route type: 'GET', data: queryParams, dataType: 'json', // Include CSRF token if you have CodeIgniter's CSRF protection enabled headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') }, success: function(response) { // Pass the fetched questions to a render function renderQuestionCards(response); }, error: function(xhr) { // Handle errors gracefully const errorMsg = xhr.responseJSON?.error || 'Failed to load questions'; console.error(errorMsg); alert(errorMsg); } }); } // Helper function to render questions in the UI function renderQuestionCards(questions) { const container = $('#exam-container'); container.empty(); // Clear existing content questions.forEach(question => { // Build HTML for each question (adjust based on your question type) const questionHtml = ` <div class="question-card mb-4 p-3 border rounded"> <h4 class="mb-3">${question.question_text}</h4> <div class="options"> <div class="mb-2"> <input type="radio" name="question-${question.id}" id="opt-a-${question.id}" value="${question.option_a}"> <label for="opt-a-${question.id}">${question.option_a}</label> </div> <div class="mb-2"> <input type="radio" name="question-${question.id}" id="opt-b-${question.id}" value="${question.option_b}"> <label for="opt-b-${question.id}">${question.option_b}</label> </div> <!-- Add more options (C/D) if your table includes them --> </div> </div> `; container.append(questionHtml); }); }
Quick Best Practices
- CSRF Protection: Always enable CodeIgniter's CSRF protection in
config.phpand include the token in your AJAX headers to prevent cross-site request forgery. - Pagination: If you have a large number of questions, add pagination parameters (
page,per_page) to the GET request and use CodeIgniter's pagination library to avoid loading too much data at once. - Input Validation: Sanitize and validate all GET parameters in the controller to prevent SQL injection (CodeIgniter's
input->get()already handles basic sanitization, but you can add more checks if needed).
内容的提问来源于stack exchange,提问作者Adis Azhar
相关产品推荐
相关产品推荐

