var backend = 'https://ntut.com.tw'; function shortenUrl() { var shortCode = $('#urlBox .short-code').val() || null; var url = $('#urlBox .target-url').val(); if (!url) { alert("網址不能是空白的!"); return; } request(shortCode, url) .done(function (res) { console.log(res); addNewRow(res); }) .fail(function (err) { console.log(err); if (err.status == 409) { alert("這個別名已經被使用了"); } else { alert("無法建立連線,請稍後再試") } }) } function addNewRow(data) { var rowHtml = '
'; rowHtml += '

ntut.com.tw/' + data.shortCode + '

'; rowHtml += '

' + data.url + '

'; rowHtml += '
'; $('#urlBox .urls').append($(rowHtml)); } function request(shortCode, url) { return $.ajax({ type: 'POST', dataType: 'json', url: backend + '/api/shortUrl', data: JSON.stringify({ shortCode: shortCode, url: url }), processData: false, contentType: 'application/json; charset=UTF-8' }) }