我使用兩個插件...jQuery的數據表:通行證返回JSON給一個變量
- Datatables(提供分頁)
- Defiant.js(提供JSON的搜索功能)
這裏是我的問題和代碼...
$(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;上面的失敗。
創建一個公共全局變量,然後當「數據」從ajax回來時,您可以將其傳遞給全局變量,然後對其運行函數,然後輸出。我會稍後發佈一個例子。 – googabeast