【问题标题】:POST request in JSON using $.ajax()使用 $.ajax() 以 JSON 格式发布请求
【发布时间】:2020-06-14 08:58:03
【问题描述】:

我的后端 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.");
    },
  });
}

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

【问题讨论】:

    标签: javascript html json ajax httprequest


    【解决方案1】:

    数据不是正确的JSON,改成:

    let data = {"article_id": id};
    

    并确保对它进行编码:

    JSON.stringify(data)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-08
      • 1970-01-01
      • 2016-11-21
      相关资源
      最近更新 更多