简体   繁体   English

如何更改Ajax请求类型和数据

[英]How to change Ajax request type and data

I'm using jQuery DataTables and I have a table that is loading data via an Ajax request. 我正在使用jQuery DataTables,并且我有一个通过Ajax请求加载数据的表。 The Ajax source is being set at initialization. 在初始化时设置Ajax源。

However, I would now like to change the request type to a POST and include a data object before I force an Ajax reload. 但是,我现在想在强制重新加载Ajax之前将请求类型更改为POST并包含一个数据对象。

I am doing something like this, but it doesn't work: 我正在做这样的事情,但是不起作用:

dt.ajax.type = 'POST';
dt.ajax.data = {<some data here>};
dt.ajax.reload();

I am only able to change the Ajax source URL, but that doesn't need to change. 我只能更改Ajax源URL,但这不需要更改。

You can use ajax option to define a function to call $.ajax method as shown below: 您可以使用ajax选项定义一个函数来调用$.ajax方法,如下所示:

$('#example').dataTable( {
  "ajax": function (data, callback, settings) {
      if(some_condition){
         data.param1 = "A";
         data.param2 = "B";
      }

      $.ajax( {
         "dataType": "json", 
         "type": (some_condition) ? "GET" : "POST", 
         "url": "/json.php", 
         "data": data, 
         "success": callback
      });
   }
});

This function will be called on initialization and every time you call ajax.reload() . 初始化时以及每次调用ajax.reload()时都会调用此函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM