jQuery REST PUT 请求在我的代码中不起作用?

jQuery REST PUT request doesn't work in my code?

我只想在 Jira 中使用 jQuery 发出 PUT 请求。 我之前用 SoapUI 试过它并且它可以工作,但是在我的 JS 文件中它不工作......它总是给我一个错误(在我的情况下用 "no" 警告)。

这是我的代码:

var issueKey = this.JIRA.Issue.getIssueKey();
var username = "admin";
var password = "admin";
var encodedLoginData = btoa(username + ":" + password);

AJS.$.ajax({
    type: 'PUT',
    contentType: 'application/json',
    url: '/jira/rest/api/2/issue/' + issueKey,
    dataType: 'json',
    async: false,
    headers: { 'Authorization': 'Basic ' + encodedLoginData },
    data: JSON.stringify('{"update":{"timetracking":[{"edit":{"originalEstimate":"4m","remainingEstimate":"3m"}}]}}'),
    success: function(response){ alert("yes"); },
    error: function(error){ alert("no"); }
});

如前所述,JSON 数据短语在 SoapUI 中有效,登录信息和 base64 加密也是如此。这都是正确的。 但我找不到我的错...有什么想法吗?

编辑:

PUT http://localhost:2990/jira/rest/api/2/issue/TEST-3 400
XMLHttpRequest.send @   batch.js?devtoolbar=…logged-in=true:5461
send    @   batch.js?locale=en-US:197
ajax    @   batch.js?locale=en-US:191
calculate   @   batch.js?devtoolbar=…logged-in=true:5620
prepareCalculation  @   batch.js?devtoolbar=…logged-in=true:5620
(anonymous) @   batch.js?devtoolbar=…logged-in=true:5620
dispatch    @   batch.js?locale=en-US:104
h   @   batch.js?locale=en-US:96
trigger @   batch.js?locale=en-US:101
simulate    @   batch.js?locale=en-US:108
e   @   batch.js?locale=en-US:114

如果这是 IIS 服务器,您可能需要禁用 WebDAV,因为它会抓取所有 PUT 请求。

我认为您的问题是 JSON.stringify 的参数不应该是字符串。尝试将其保存到一个变量中,然后对其进行 JSON.stringify。

考虑 JSON.stringify 的结果。例如:

 JSON.stringify("{}"); //""{}""

 JSON.stringify({}); //"{}"

现在你的代码应该是这样的 例如:

var issueKey = this.JIRA.Issue.getIssueKey();
var username = "admin";
var password = "admin";
var encodedLoginData = btoa(username + ":" + password);
var dataObject = {"update":{"timetracking":[{"edit":{"originalEstimate":"4m","remainingEstimate":"3m"}}]}};

AJS.$.ajax({
    type: 'PUT',
    contentType: 'application/json',
    url: '/jira/rest/api/2/issue/' + issueKey,
    dataType: 'json',
    async: false,
    headers: { 'Authorization': 'Basic ' + encodedLoginData },
    data: JSON.stringify(dataObject),
    success: function(response){ alert("yes"); },
    error: function(error){ alert("no"); }
});

恰好是你的错误是你试图对字符串进行字符串化

data: JSON.stringify('{update...}')

如今,您不需要 jQuery 在浏览器中执行 HTTP。所有现代浏览器都内置了 Fetch API

const issueKey = this.JIRA.Issue.getIssueKey();
const username = "admin";
const password = "admin";
const encodedLoginData = btoa(username + ":" + password);

const body = {
  update: {
    timetracking: [{
      edit: {
        originalEstimate: "4m"
        remainingEstimate: "3m"
      }
    }]
  }
}

fetch(`/jira/rest/api/2/issue/${issueKey}`, {
  method: 'PUT',
  body: JSON.stringify(body),
  headers: {
    'Authorization': 'Basic ' + encodedLoginData
    'Content-Type': 'application/json',
  },
})
  .then(response => alert('yes'))
  .catch(error => alert('no'));