用Ajax帖子发送JSON对象

发布于 2025-02-06 16:11:36 字数 1549 浏览 2 评论 0原文

我正在研究一个项目,我们尝试通过Ajax在UI和RESTAPI之间交换不同的参数。 RESTAPI定义数据必须如何:

”要发送的参数“

“在此处输入图像说明”

我尝试以这种方式求解它:

 $(document).ready(function(){
  $("#submit").click(function(){
      var credentials = [
          {user_name: $("#uname").val(),
            password: $("#pwd").val()
          }
      ];
      alert(credentials);
      $.ajax({
          url:"../rest/user/login",
          type:"POST",
          data:JSON.stringify({credentials: credentials}),
          success: function(){
            window.location.href = "startrackhome.html";
          },
          error:  function error(response){
            try{
              var json = JSON.parse(response.responseText);
              if(typeof json.message === 'undefined'){
                throw new Error("Response json has no message");
              }
              else{
                alert(json.message);
              }
            }
          catch(ex){
            alert("unexpected error (code:" + response.status +")");
          }
        }

      });
   });
   });

该警报显示以下内容:[object object object]

,我始终收到一个错误消息(错误:400),这意味着我犯了一个错误,我认为我的sendig格式是错误的,但我不知道如何解决它。

希望您能帮助我! :)

Im working on a project, where we try to exchange different parameters between the UI and a RestAPI via AJAX. The RestAPI defines how the data has to look:

Parameters to send

enter image description here

I tried to solve it this way:

 $(document).ready(function(){
  $("#submit").click(function(){
      var credentials = [
          {user_name: $("#uname").val(),
            password: $("#pwd").val()
          }
      ];
      alert(credentials);
      $.ajax({
          url:"../rest/user/login",
          type:"POST",
          data:JSON.stringify({credentials: credentials}),
          success: function(){
            window.location.href = "startrackhome.html";
          },
          error:  function error(response){
            try{
              var json = JSON.parse(response.responseText);
              if(typeof json.message === 'undefined'){
                throw new Error("Response json has no message");
              }
              else{
                alert(json.message);
              }
            }
          catch(ex){
            alert("unexpected error (code:" + response.status +")");
          }
        }

      });
   });
   });

The alert shows this: [object Object]

And I always get an error message (error: 400), which means that I mus have made a mistake and I think the format I'm sendig is wrong but I dont know how to fix it.

I hope you can help me! :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅浅 2025-02-13 16:11:38

我对您的代码进行了一些更改:


// credentials is an object
var credentials = {
    user_name: $("#uname").val(),
    password: $("#pwd").val()
}
alert(credentials);
$.ajax({
    // check this url seems a bit off
    url: "../rest/user/login",
    type: "POST",
    data: {
        credentials: credentials
    },
    success: function() {
        window.location.href = "startrackhome.html";
    },
    error: function error(response) {
        try {
            var json = JSON.parse(response.responseText);
            if (typeof json.message === 'undefined') {
                throw new Error("Response json has no message");
            } else {
                alert(json.message);
            }
        } catch (ex) {
            alert("unexpected error (code:" + response.status + ")");
        }
    }

});

在我的情况下,它提出了此请求:

fetch("https://stackoverflow.com/posts/rest/user/login", {
  "headers": {
    "accept": "*/*",
    "accept-language": "",
    "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Linux\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "x-requested-with": "XMLHttpRequest"
  },
  "referrer": "https://stackoverflow.com/posts/72620005/edit",
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": "credentials%5Buser_name%5D=test&credentials%5Bpassword%5D=test",
  "method": "POST",
  "mode": "cors",
  "credentials": "include"
});
credentials[user_name]: test
credentials[password]: test

这似乎不错,如果服务器需要JSON,则可以将凭据串起,这给出了此Paylaod:

credentials: {"user_name":"test","password":"test"}

I made some changes to your code :


// credentials is an object
var credentials = {
    user_name: $("#uname").val(),
    password: $("#pwd").val()
}
alert(credentials);
$.ajax({
    // check this url seems a bit off
    url: "../rest/user/login",
    type: "POST",
    data: {
        credentials: credentials
    },
    success: function() {
        window.location.href = "startrackhome.html";
    },
    error: function error(response) {
        try {
            var json = JSON.parse(response.responseText);
            if (typeof json.message === 'undefined') {
                throw new Error("Response json has no message");
            } else {
                alert(json.message);
            }
        } catch (ex) {
            alert("unexpected error (code:" + response.status + ")");
        }
    }

});

in my case it makes this request :

fetch("https://stackoverflow.com/posts/rest/user/login", {
  "headers": {
    "accept": "*/*",
    "accept-language": "",
    "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    "sec-ch-ua": "\" Not A;Brand\";v=\"99\", \"Chromium\";v=\"102\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Linux\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "x-requested-with": "XMLHttpRequest"
  },
  "referrer": "https://stackoverflow.com/posts/72620005/edit",
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": "credentials%5Buser_name%5D=test&credentials%5Bpassword%5D=test",
  "method": "POST",
  "mode": "cors",
  "credentials": "include"
});
credentials[user_name]: test
credentials[password]: test

which seems good, if the server needs a json, you can stringify the credentials, which gives this paylaod :

credentials: {"user_name":"test","password":"test"}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文