新增縮網址服務

This commit is contained in:
2021-08-02 01:27:24 +08:00
parent c9b18b2ed4
commit 9205528f97
3 changed files with 98 additions and 10 deletions

54
js/main.js Normal file
View File

@ -0,0 +1,54 @@
'use strict'
let backend = 'https://ntut.com.tw'
const shortenUrl = async () => {
let shortCode = $('#urlBox .short-code')[0].value || null
let url = $('#urlBox .target-url')[0].value
if (!url) {
alert("URL is empty!")
return
}
request({ shortCode, url })
.done((res) => {
console.log(res)
addNewRow(res)
})
.fail((err) => {
console.log(err)
if (err.status == 409) {
alert("This code has been used.")
}
else {
alert("Failed to establish connection.")
}
})
}
const addNewRow = (data) => {
let view = $('#urlBox .urls')
view.append($(`
<div class="url row">
<p class="text-center col-md-4 col-6">ntut.com.tw/${data.shortCode}</p>
<p class="text-center col-md-8 col-6">${data.url}</p>
</div>
`))
}
const request = ({ shortCode, url }) => {
return $.ajax({
type: 'POST',
dataType: 'json',
url: `${backend}/api/shortUrl`,
data: JSON.stringify({
shortCode, url
}),
processData: false,
contentType: 'application/json; charset=UTF-8'
})
}