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

如何通过JS将Bootstrap搜索栏的SQL查询发送至后端?

实现思路与代码示例

前端部分(Bootstrap + 原生JS)

先搭建Bootstrap页面结构,绑定点击事件触发请求,这里提供两种常用的前端请求方案:

Bootstrap页面结构

<div class="container mt-5">
  <div class="mb-3">
    <label for="sqlQuery" class="form-label">输入SQL查询语句</label>
    <textarea class="form-control" id="sqlQuery" rows="5" placeholder="例如:SELECT * FROM users WHERE id = 1;"></textarea>
  </div>
  <button onclick="executeSqlQuery()" class="btn btn-primary">执行查询</button>
  <div class="mt-4" id="resultContainer"></div>
</div>

方案1:原生AJAX实现请求

function executeSqlQuery() {
  const sql = document.getElementById('sqlQuery').value.trim();
  if (!sql) {
    alert('请输入SQL查询语句');
    return;
  }

  const xhr = new XMLHttpRequest();
  xhr.open('POST', '/api/execute-sql', true); // 替换为你的后端接口地址
  xhr.setRequestHeader('Content-Type', 'application/json');

  xhr.onload = function() {
    if (xhr.status >= 200 && xhr.status < 300) {
      const result = JSON.parse(xhr.responseText);
      document.getElementById('resultContainer').innerHTML = `<pre>${JSON.stringify(result, null, 2)}</pre>`;
    } else {
      alert('查询失败:' + xhr.responseText);
    }
  };

  xhr.onerror = function() {
    alert('网络错误,请检查后端服务是否正常');
  };

  xhr.send(JSON.stringify({ query: sql }));
}

方案2:Fetch API实现请求(更简洁)

async function executeSqlQuery() {
  const sql = document.getElementById('sqlQuery').value.trim();
  if (!sql) {
    alert('请输入SQL查询语句');
    return;
  }

  try {
    const response = await fetch('/api/execute-sql', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ query: sql })
    });

    if (!response.ok) {
      throw new Error(await response.text());
    }

    const result = await response.json();
    document.getElementById('resultContainer').innerHTML = `<pre>${JSON.stringify(result, null, 2)}</pre>`;
  } catch (error) {
    alert('查询失败:' + error.message);
  }
}

后端核心注意事项

  • 必须处理SQL注入风险:
    • 严格限制查询类型(仅允许SELECT类只读操作,禁止INSERT/UPDATE/DELETE等写操作)
    • 对输入SQL做语法校验与危险字符过滤
    • 优先使用后端语言的参数化查询能力(比如Java的PreparedStatement、Python的psycopg2参数化)
  • 后端接口需接收POST请求,解析JSON格式的query参数,执行查询后返回JSON格式结果
  • 捕获查询过程中的异常(语法错误、权限问题等),返回清晰的错误提示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:21:15