POST 在 JSON 中使用 $.ajax() 请求

POST request in JSON using $.ajax()

我的后端 API 接受 JSON 格式的数据,例如:

{ "article_id" = 1 }

在前端,我尝试将以下 javascript 添加到按钮中:

function articleIsSelected(id) {
  let data = '{"article_id":' + id + '}';

  $.ajax({
    url:"https://www.myurl.com",
    data: data,
    type: "post",
    contentType: "application/json",

    success: function () {
      alert("Selection succeeded!");
    },
    error: function () {
      alert("Selection failed.");
    },
  });
}

returns请求成功,但我的数据库没有更新。数据格式有问题。与其尝试以 JSON 格式对数据进行硬编码,不如将值签名为 "article_id",然后 JSON 使用 JSON.stringify(data).

对其进行编码

数据不对JSON,改成:

let data = {"article_id": id};

并确保对其进行编码:

JSON.stringify(data)