如何在JSFiddle中模拟Ajax请求

时间:2019-04-26 16:57:58

标签: javascript jquery ajax datatables jsfiddle

我有一个JSFiddle:https://jsfiddle.net/9z362cLj/6/。我正在尝试模拟这样的Ajax请求:

var json_data = {"recordsTotal":23286,"recordsFiltered":23286,
"data":[{"id":104,"activity_type":"Option 1",}],
"draw":1,
"options":{"activity_type":[{"label":"Option 1","value":1},
                            {"label":"Option 2","value":2},]}}

console.log(json_data.data)

var oTable = $('#example').DataTable({
    serverSide: true,
    ajax: {url: "/echo/json/",
                type: "POST",
          data: json_data
        },
});

yadcf.init(oTable,
      [
        {
          column_number : 0,
          filter_type: "range_date",
        },
        {
          column_number : 1,
          filter_type: "select",
          select_type: "select2",
        },
       ]);

json_data的格式为Ajax请求在我的实际项目中收到的实际响应。但是,DataTable中什么都没有显示。我如何使数据出现在数据表中?

1 个答案:

答案 0 :(得分:0)

嗨,您可以尝试像我创建的jsfiddle

或将您的json响应添加为这样的字符串:

数据:{

json:'{"status":"success","message":"Hello World"}'

},

编辑:

我纠正了小提琴中的几件事,例如json中的“,”和ajax中的列定义:

    var json_data = {
"data":[{"id":104,"activity_type":"Option 1"}, {"id":102,"activity_type":"option 2"}],
"recordsTotal":23286,"recordsFiltered":23286,
"draw":1,
"options":{"activity_type":[{"label":"Option 1","value":1},
                            {"label":"Option 2","value":2}]}};       
console.log(json_data)
var oTable = $('#example').DataTable({
    serverSide: true,
    ajax: {url: "/echo/json/",
                type: "POST",
          data:{ json : JSON.stringify(json_data) }
          },
           "columns": [
            { "data": "id" },
            { "data": "activity_type" }
        ]
});

yadcf.init(oTable,
      [
        {
          column_number : 0,
          filter_type: "range_date",
        },
        {
          column_number : 1,
          filter_type: "select",
          select_type: "select2",
        },
       ]);

希望对您有帮助=)