|
| 1 | +// @ts-nocheck |
| 2 | +$(document).ready(function () { |
| 3 | + function jsEscape(str) { |
| 4 | + // This method is used to prevent user from XSS (cross-site scripting) attack. |
| 5 | + // NOTE: We are using this method instead of $(selector).text() provided by jQuery becuase of whitespace issue with it. (https://forum.jquery.com/topic/inserting-whitespace-into-a-textnode) |
| 6 | + |
| 7 | + var tagsToReplace = { |
| 8 | + "&": "&", |
| 9 | + "<": "<", |
| 10 | + ">": ">", |
| 11 | + '"': """, |
| 12 | + "'": "'", |
| 13 | + "/": "/", |
| 14 | + "`": "`", |
| 15 | + "=": "=", |
| 16 | + }; |
| 17 | + |
| 18 | + if (typeof str === "string") { |
| 19 | + return str.replace(/[&<>"'`=\/]/g, function (tag) { |
| 20 | + return tagsToReplace[tag]; |
| 21 | + }); |
| 22 | + } else { |
| 23 | + return str; |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + $.ajax({ |
| 28 | + url: "https://run.mocky.io/v3/e11e89e4-f328-4d3c-974d-b6707e9f27df", // Mock api (just for testing). |
| 29 | + type: "GET", |
| 30 | + dataType: "json", |
| 31 | + success: function (res) { |
| 32 | + console.log(res); |
| 33 | + |
| 34 | + // This code generates table from the data provided by this http call. |
| 35 | + const caption = "Codility Table"; |
| 36 | + let $table = $("<table><caption>" + caption + "</caption></table>"); |
| 37 | + |
| 38 | + let tr_1 = "<tr><td id='blank_td'></td>"; |
| 39 | + res.headers.forEach(function (item, index) { |
| 40 | + tr_1 += "<th scope='col'>" + jsEscape(item) + "</th>"; |
| 41 | + }); |
| 42 | + tr_1 += "</tr>"; |
| 43 | + $table.append(tr_1); |
| 44 | + |
| 45 | + for (const [key, value] of Object.entries(res.data)) { |
| 46 | + var other_tr = "<tr>"; |
| 47 | + other_tr += "<th scope='row'>" + jsEscape(key) + "</th>"; |
| 48 | + value.forEach(function (item, index) { |
| 49 | + other_tr += "<td class='my_td'>" + jsEscape(item) + "</td>"; |
| 50 | + }); |
| 51 | + other_tr += "</tr>"; |
| 52 | + $table.append(other_tr); |
| 53 | + } |
| 54 | + |
| 55 | + $("#my_table").append($table); |
| 56 | + }, |
| 57 | + error: function (err) { |
| 58 | + // Error occured. |
| 59 | + console.log(err); |
| 60 | + alert("Something went wrong. Please try again later."); |
| 61 | + }, |
| 62 | + }); |
| 63 | +}); |
0 commit comments