0%

[JavaScript] 應用

紀錄開發上常遇到的問題,避免重複踩坑。

使用format格式化字串

1
2
var name = 'Mike';
console.log(`Hello ${name}`);

檢查jQuery元素是否存在

1
2
3
if ($("#selector").length) {
console.log("exists");
}

使用ajax POST傳送json資料給server

1
2
3
4
5
6
7
8
9
$.ajax({
type: "POST",
url: "test",
data: { name: "Mike" },
contentType: "application/json;charset=utf-8",
success: function (response) {
console.log(response);
}
});

DataTables動態欄位

參考https://datatables.net/forums/discussion/60722/dynamic-columns

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$(function() {
var genColumns = function(data) {
var columns = [];
var columnNames = Object.keys(data[0]);
for (var i in columnNames) {
columns.push({data: columnNames[i], title: columnNames[i]});
}
return columns;
}
$.ajax({
url: "test",
success: function (response) {
$("#dt").DataTable({
data: response,
columns: genColumns(response)
});
}
});
});