You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于AJAX实现Bootstrap Modal的JavaScript改造需求

Alright, let's tweak your code to implement the Bootstrap modal-based editing workflow instead of redirecting to a new page. Here's a complete, working solution with explanations:

Step 1: Update the HTML (Add Modal & Form Template)

First, add a hidden Bootstrap modal to your page that will hold the edit form. We'll reuse this modal instead of creating it from scratch every time:

<!-- Table container -->
<table id="table" class="table table-striped"></table>

<!-- Bootstrap Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editModalLabel">Edit Data Entry</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form id="editForm">
          <!-- Hidden field to store the entry ID (for saving later) -->
          <input type="hidden" id="editId" name="id">
          
          <div class="form-group">
            <label for="editName">Name:</label>
            <input type="text" class="form-control" id="editName" name="name" placeholder="Enter name">
          </div>
          
          <div class="form-group">
            <label for="editDescription">Description:</label>
            <textarea class="form-control" id="editDescription" name="description" rows="4" placeholder="Enter description"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" onclick="saveEdit()">Save Changes</button>
      </div>
    </div>
  </div>
</div>

Step 2: Modify the JavaScript Functions

Update your edit() function to populate the modal instead of redirecting, and add a saveEdit() function to handle form submission:

// Fix: Corrected HTML escaping issues in row generation
function populateData(dataInput) {
  var row = $(`<tr id="${dataInput.id}"/>`);
  $('#table').append(row);
  row.append($(`<td>${dataInput.name}</td>`));
  row.append($(`<td>${dataInput.description}</td>`));
  row.append($(
    `<td><input type="button" class="btn btn-warning" value="Edit" onclick="edit(${dataInput.id})"/></td>`
  ));
}

// Updated edit function: Fetch data and populate modal
function edit(id) {
  $.ajax({
    type: 'GET',
    url: `/getData?id=${id}`,
    dataType: 'json', // Let jQuery auto-parse the JSON response
    success: function(rows) {
      const dataInput = rows[0];
      
      // Fill modal form fields with fetched data
      $('#editId').val(dataInput.id);
      $('#editName').val(dataInput.name);
      $('#editDescription').val(dataInput.description);
      
      // Show the Bootstrap modal
      $('#editModal').modal('show');
    },
    error: function(xhr, status, err) {
      console.error('Failed to load data:', err);
      alert('Oops, couldn\'t load the data for editing.');
    }
  });
}

// New function: Handle saving edited data via AJAX
function saveEdit() {
  const formData = {
    id: $('#editId').val(),
    name: $('#editName').val(),
    description: $('#editDescription').val()
  };

  $.ajax({
    type: 'POST',
    url: '/saveEditedData', // Replace with your actual save endpoint
    data: formData,
    success: function(response) {
      $('#editModal').modal('hide');
      alert('Data saved successfully!');
      
      // Optional: Refresh the table or update the specific row to reflect changes
      // updateTableRow(formData.id, formData.name, formData.description);
    },
    error: function(xhr, status, err) {
      console.error('Failed to save data:', err);
      alert('Oops, couldn\'t save your changes.');
    }
  });
}

Step 3: Optimize the Backend /getData Endpoint

You can simplify your endpoint to directly return JSON (no need to stringify manually):

app.get('/getData', function(req, res, next) {
  mysql.pool.query('SELECT * FROM dataTable WHERE id=?', [req.query.id],
    function(err, rows, fields) {
      if (err) {
        next(err);
        return;
      }
      // Express automatically converts objects/arrays to JSON
      res.json(rows);
    });
});

Key Changes Explained:

  1. Modal Reuse: We define the modal once in HTML instead of generating it dynamically, which is cleaner and more performant.
  2. No Page Redirect: The edit() function now fetches data and populates the modal instead of sending the user to a new page.
  3. Form Data Handling: A hidden id field keeps track of the entry being edited, making it easy to submit updates to the backend.
  4. Error Handling: Added basic error alerts and console logs to help debug issues with AJAX calls.
  5. Cleaner DOM Generation: Used template literals (`) in populateData for more readable HTML generation, and fixed the escaped < characters.

内容的提问来源于stack exchange,提问作者termlim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:18:07