我现在有一个网络应用程序,它可以呈现项目列表。
基本上,在 div 单击时,我想发送一个仅修改 JSON 对象的 Like 值的 put 请求。
这是我的数据现在的结构:
{
"id": 1,
"title": "test-1",
"description": "test-1",
"likes": [
"username-1",
"username-2"
]
},
{
"id": 2,
"title": "test-2",
"description": "test-2",
"likes": [
"username-1",
"username-2"
]
}
所以所有这些都是同时渲染的,并且每个的侧面都会有一个“赞”按钮。当有人点击“喜欢”按钮时,我想向我的 API 发送一个 put 请求,通过将他们的用户名添加到“喜欢”来修改具有相同 id 的 JSON 对象。
感谢您的帮助,谢谢
您有两个选择:
- 将 PUT 请求异步发送到您的 API(例如通过 JQuery),然后等待 API 的响应(无论成功与否),然后检索新的 JSON 数据。
- 将 PUT 请求异步发送到您的 API,并强制 JSON 数据将新用户名包含到点赞数据中。
第一个选项更好,因为它可以处理其他用户所做的所有更改(新的喜欢或删除的喜欢)。
在 JQuery 中,您可以在“点击时”事件处理中使用以下代码:
$.ajax({
type: 'POST', // Use POST with X-HTTP-Method-Override or directly a PUT if the browser/client supports it
dataType: 'json', // If your request format is JSON
url: "http://your-api-url", // Your API URL
headers: {"X-HTTP-Method-Override": "PUT"}, // You should override this if you used "POST" early X-HTTP-Method-Override set to PUT
data: '{"username": "theNewUsername"}', // The username/userId of the user who clicked the button
success: callback, // The JS function which modifies the JSON data by adding the username/userID to the JSON data or by changing all the JSON data to a new one
});
Tôi là một lập trình viên xuất sắc, rất giỏi!