cuốn sách gpt4 ai đã làm

javascript - 如何仅使用按钮或 div 向我的 API 发送 put 请求?

In lại Tác giả: Walker 123 更新时间:2023-11-28 05:46:40 25 4
mua khóa gpt4 Nike

我现在有一个网络应用程序,它可以呈现项目列表。

基本上,在 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 对象。

感谢您的帮助,谢谢

câu trả lời hay nhất

您有两个选择:

  1. 将 PUT 请求异步发送到您的 API(例如通过 JQuery),然后等待 API 的响应(无论成功与否),然后检索新的 JSON 数据。
  2. 将 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
});

关于javascript - 如何仅使用按钮或 div 向我的 API 发送 put 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38466844/

25 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress