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

DataTables服务器端处理时自动添加"_"查询参数的原因及去除方法

DataTables服务器端请求自动添加_查询参数的原因及解决方法

问题描述

我在初始化服务器端处理的DataTables时,发现AJAX请求自动添加了一个_查询参数,但我在代码里定义的requestBody中并没有包含这个参数。以下是我的初始化代码:

let draw; //Draw Variable For datatable
const policytable = $("#policyTable").DataTable({ //Initialising PolicyList Table
  processing: true,
  serverSide: true,
  pagingType: "simple_numbers",
  rowId: "_id",
  ajax: {
    url: `SomeURL`,
    type: "GET",
    datatype: "json",
    data: function(d) {
      draw = d.draw;
      let requestBody = {
        from: d.start,
        size: d.length,
        activeStatus: true,
        sortBy: d.columns[d.order[0].column].name,
        orderBy: d.order[0].dir
      };
      if (d.search.value) {
        requestBody.keyword = d.search.value;
      };
      console.log("REQUEST BODY", requestBody);
      return (requestBody);
    },
    crossDomain: true,
    xhrFields: {
      withCredentials: true
    },
  },
  order: [1, "asc"],
  columnDefs: [{
    targets: 0,
    orderable: false,
    searchable: false,
    width: "3%",
    className: "select-checkbox",
    checkboxes: { selectRow: true }
  }],
  select: {
    style: "multi",
    selector: "td:first-child"
  },
  columns: [{
    defaultContent: "",
  }, {
    title: "Name",
    name: "name",
    data: "name"
  }]
});

我已经查阅了DataTables官方文档,但没找到相关解释。想请教这个_参数是什么,以及如何避免它被作为请求参数发送?


解答

那个自动添加的_参数是用来阻止浏览器缓存AJAX请求的随机时间戳,本质上是jQuery AJAX的默认行为(DataTables底层依赖jQuery AJAX实现)。对于GET请求,jQuery会自动附加这个参数,确保每次请求的URL都是唯一的,避免浏览器返回缓存的旧响应。

要避免发送这个参数,你可以用以下两种方法:

方法1:启用AJAX缓存

在你的ajax配置中添加cache: true选项,这样jQuery就不会自动生成并附加_参数了:

ajax: {
  url: `SomeURL`,
  type: "GET",
  datatype: "json",
  cache: true, // 启用缓存,阻止添加_参数
  data: function(d) {
    // 你的现有代码...
  },
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  },
},

方法2:切换为POST请求(可选)

如果你不需要GET请求的特性,可以把请求类型改为POST。jQuery AJAX默认不会给POST请求添加_参数,这样也能解决问题:

ajax: {
  url: `SomeURL`,
  type: "POST", // 改为POST请求
  datatype: "json",
  data: function(d) {
    // 你的现有代码...
  },
  crossDomain: true,
  xhrFields: {
    withCredentials: true
  },
},

需要注意的是,如果选择POST请求,你需要确保后端接口支持接收POST类型的请求参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 18:58:11