我正在玩 jQuery 和 Javascript。使用 li 專案和此 API 處理 TODOs 應用程式:https ://jsonplaceholder.typicode.com/todos 。我從這個 API 收到 200 個專案。我正在嘗試發布通過單擊按鈕(btn-add)創建的新專案,并且一切都按預期作業,但發布請求將“標題”屬性保留為空白。這是我的 HTML 和 JS 代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="/CSS/styles.css" rel="stylesheet">
<title>TO DO List</title>
<link href="https://fonts.googleapis.com/icon?family=Material Icons" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="/JS/index.js"></script>
</head>
<body>
<div id="inputDIV">
<input id="input" type="text" placeholder="Enter new item">
</div>
<div id="buttons">
<button id="btn-add">Add List Item</button>
<button id="btn-update">Update First Item</button>
<button id="btn-delete">Delete First Item</button>
</div>
<div id="ulDIV">
<ul id="list">
<!-- Here we will insert the list items via JS-->
</ul>
</div>
</body>
</html>
$(document).ready(function(){
let inputNew = $('#input');
let list = $('#list');
let currentInputValue = "";
$('#btn-add').click(createTODOItemAtBackend);
inputNew.on({
"input": function(e){
console.log(e.target.value);
currentInputValue = e.target.value;
},
"keyup": function(e){
if(e.keyCode === 13){
createTODOItemAtBackend();
}
}
})
getTODOListFromBackend();
function clearInputData(){
inputNew.val("");
currentInputValue = "";
}
function createTODODynamically(id, title){
let newListElement = document.createElement("li");
let textNode = document.createTextNode(title);
newListElement.appendChild(textNode);
newListElement.id = id;
return newListElement;
}
function getTODOListFromBackend(){
$.get("https://jsonplaceholder.typicode.com/todos", function(data, status){
let response = data;
for(let i=0; i < response.length; i ){
list.append(createTODODynamically(response[i].id, response[i].title));
}
});
}
let obj = {
"userId": 1,
"title": currentInputValue,
"completed": false
};
function createTODOItemAtBackend(){
$.post("https://jsonplaceholder.typicode.com/todos", obj, function(data, status){
let response = data;
list.append(createTODODynamically(response.id, currentInputValue));
console.log("Item Added to the list!");
clearInputData();
});
}
})
這就是我在網路瀏覽器中閱讀帖子資訊時看到的內容:
{userId: "1", title: "", completed: "false", id: 201}
completed: "false"
id: 201
title: ""
userId: "1"
有人可以幫助我,為什么屬性“標題”被發布為空?提前致謝
uj5u.com熱心網友回復:
答案就在@epascarello 對 OP 評論的暗示中。您設定currentInputValue了輸入值何時更改,但沒有代碼將此值更新為obj.
"input": function(e){
console.log(e.target.value);
currentInputValue = e.target.value;
//Add this line
obj.title = e.target.value;
},
currentInputValue附加說明:如果你重構你的代碼,你真的不需要,使用obj應該可以完成這項作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/441715.html
標籤:javascript html jQuery
下一篇:在C 中使用極坐標函式計算阻抗
