如何通过AJAX调用jQuery DataTable传递额外参数
我使用以下代码传递参数,如DataTable Documentation所示。如何通过AJAX调用jQuery DataTable传递额外参数
查看:
$('#example').dataTable({
"ajax": {
"url": "/Student/GetStudents",
"data": function (d) {
d.test= "some data";
}
}
});
控制器:
public ActionResult GetStudents(JQueryDataTableParamModel param, string test)
{
//code omitted for brevity
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = allRecords.Count(),
iTotalDisplayRecords = filteredRecords.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
虽然 “测试” 参数传递到控制器,“参数”参数中的值为空或0,并导致数据表返回空数据。另一方面,如果我在数据表参数中使用下面的行而不是AJAX调用,则param的所有值都会正确传递给控制器(但使用AJAX调用并且此行也会导致错误)。我需要传递额外的参数给控制器,并且必须使用AJAX调用。我怎样才能传递参数值?
"ajaxSource": "/Student/GetStudents",
您可以创建一个json数据字符串,您可以在其中传递额外的参数。
var data = {'test':"some data","test1":"some data1"};
$('#example').dataTable({
"ajax": {
"url": "/Student/GetStudents",
"data": data
}
});
我已经可以将参数传递给控制器,但它会导致参数参数传递为null或0.通过使用您的示例,会出现相同的结果,我只需要传递param值而不使用**“ajaxSource”:“/ Student/GetStudents“**线。任何想法? –
使用JSON.stringify(数据)并发送数据。在控制器结束使用JSON.parse(params)解析参数。检查它是否正在工作..? –
请问您可以通过以下两种方式更新您的答案:AJax调用和控制器(stringfy转换)。 –
JavaScript代码:
$('#example').dataTable({
"ajax": {
"url": "/Student/GetStudents",
type: 'GET',
data: {
test1: "This test1 data ",
test2: "This test2 data"
}
}
});
public ActionResult GetStudents(JQueryDataTableParamModel param, string test)
{
//code omitted for brevity
//printing in params in controller with asp.net code.
print_r("Data from" ,param.test1 ,param.test2);
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = allRecords.Count(),
iTotalDisplayRecords = filteredRecords.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
关于[this]的任何ide(http://stackoverflow.com/questions/40571553/jquery-datatable-individual-column-searching-on-table-header)问题? –
var finalArray = [];
var data = {'test':"some data","test1":"some data1"};
finalArray.push(data);
var rec = JSON.stringify(finalArray);
$('#example').dataTable({
"ajax": {
"url": "/Student/GetStudents",
"data": rec
}
});
public ActionResult GetStudents(JQueryDataTableParamModel param,string test)
{
//code omitted for brevity
//printing in params in controller with asp.net code.
print_r(json_decode(param));
return Json(new
{
sEcho = param.sEcho,
iTotalRecords = allRecords.Count(),
iTotalDisplayRecords = filteredRecords.Count(),
aaData = result
},
JsonRequestBehavior.AllowGet);
}
最后,我通过使用fnServerData方法如下所示解决了这个问题。
"ajaxSource": "/Student/GetStudents",
//fnServerData used to inject the parameters into the AJAX call sent to the server-side
"fnServerData": function (sSource, aoData, fnCallback) {
aoData.push({ "name": "test", "value": "some data" });
$.getJSON(sSource, aoData, function (json) {
fnCallback(json)
});
},
...
无论如何,非常感谢有用的答案。投票+有用的...
有关这个问题的任何想法? –