參考網址:
用VScode+EasyCod(ChatGPT)所產生的程式
運用到拖曳調整道次
問題1:用javascript ajax 讓籤號可以拖曳,並交換內容
問題2:可以加入ajax功能嗎?要更改資料庫內容
<!-- 20230408 by ChatGPT -->
<style>
.tags {
display: flex;
flex-wrap: wrap;
}
.tag {
padding: 10px;
margin: 10px;
background-color: #ccc;
cursor: move;
}
</style>
<div class="tags" id="container">
<div class="tag" draggable="true" ondragstart="drag(event)" data-id="1">Tag 1</div>
<div class="tag" draggable="true" ondragstart="drag(event)" data-id="2">Tag 2</div>
<div class="tag" draggable="true" ondragstart="drag(event)" data-id="3">Tag 3</div>
<div class="tag" draggable="true" ondragstart="drag(event)" data-id="4">Tag 4</div>
</div>
<script type="text/javascript">
var dragSrcEl = null;
function drag(e) {
dragSrcEl = e.target;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.setData('text/html', dragSrcEl.innerHTML);
}
function drop(e) {
e.preventDefault();
if (e.target.className == 'tag') {
var temp = dragSrcEl.innerHTML;
dragSrcEl.innerHTML = e.target.innerHTML;
e.target.innerHTML = temp;
// 更新資料庫內容
var id1 = dragSrcEl.getAttribute('data-id');
var id2 = e.target.getAttribute('data-id');
console.log(id1);
updateDatabase(id1, id2);
}
}
function allowDrop(e) {
e.preventDefault();
}
var container = document.getElementById('container');
container.addEventListener('drop', drop, false);
container.addEventListener('dragover', allowDrop, false);
function updateDatabase(id1, id2) {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'update.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send('id1=' + id1 + '&id2=' + id2);
}
</script>