我用了两个插件..。
这是我的问题和密码..。
$(document).ready(function() {
var myjson;
//Initialize Datatable
var newtable = $('#pdf-results').DataTable({
"ajax": {
"url": "http://www.example.com/home/Dummy_JSON_data.js",
"dataSrc": function(json) {
myjson: json; // This is the problem. I am not sure how to assign returned JSON to a variable ?
}
}
});
// On button click, pass the returned JSON results to Defiant code below for searching and redraw Datatable.
$("button").click(function() {
var cname = $("#name").val();
console.log('cname', cname);
var cyear = $("#year").val();
var rawXPath_cName = '//*[(contains(courseName, "' + cname + '") or contains(courseCode, "' + cname + '")) and contains(Year, "' + cyear + '")]';
//console.log(rawXPath_cName);
try {
var reds = JSON.search(myjson, rawXPath_cName);
var table_body = '';
for (var i = 0; i < reds.length; i++) {
table_body += '<tr>';
table_body += '<td>' + reds[i].courseCode + '</td>';
table_body += '<td>' + reds[i].courseName + '</td>';
table_body += '<td>' + reds[i].Year + '</td>';
table_body += '<td>' + reds[i].Trimester + '</td>';
table_body += '<td><a href = ' + reds[i].pdfURL + '>Download map</a></td>';
table_body += '</tr>';
}
$("tbody").empty();
$("tbody").append(table_body);
newtable.ajax.reload(); // Also, not sure if this is required or not.
//When the table redraws based on user search query, datatables doesn't display pagination correctly. It sometimes it shows 4-5 rows on page 1 and 4-5 rows on page 2, instead of showing upto 10 rows on page 1, which is the default behavior.
} catch (e) {
console.log('No results found');
}
});
});
我需要将Ajax调用返回的数据分配给一个变量,这样我就可以在defiant.js代码中使用这些结果来搜索结果集。本质上,上面的代码myjson: json;失败了。
发布于 2017-03-10 02:23:01
我希望我正确地阅读了API,但是看起来您想要使用ajax.json() - https://datatables.net/reference/api/ajax.json()
var newtable = $('#pdf-results').DataTable({
"ajax": {
"url": "http://www.example.com/home/Dummy_JSON_data.js"
}
});
//new code
newtable.on('xhr', function(){
var json = newtable.ajax.json();
myjson = json.data; //bind to global variable
alert(json.data);
});发布于 2017-03-10 14:41:02
根据医生们,它应该简单地声明一个全局变量(在本例中为myjson),并在dataSrc函数中将JSON数据分配给它:
var newtable = $('#pdf-results').DataTable({
"ajax": {
"url": "http://www.example.com/home/Dummy_JSON_data.js",
"dataSrc": function(json) {
myjson = json; // '=', not ':'
return json;
}
}
});在您的代码中,您试图使用:而不是=将json分配给变量。也许这就是它失败的原因?
另外,不要忘记返回dataSrc函数中的数据,这样DataTables就可以使用它了。
https://stackoverflow.com/questions/42708835
复制相似问题