【问题标题】:Sending a json object with ajax post使用 ajax post 发送 json 对象
【发布时间】:2022-06-14 23:53:56
【问题描述】:

我正在做一个项目,我们尝试通过 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]

而且我总是收到一条错误消息(错误:400),这意味着我一定犯了一个错误,我认为我发送的格式是错误的,但我不知道如何修复它。

我希望你能帮助我! :)

【问题讨论】:

  • 我认为你不应该将 json 字符串化,而是将对象按原样传递给 $.ajax,并添加 contentType: "application/json"
  • 我试过了,但我仍然收到错误消息,所以这不是我猜的解决方案
  • 你的服务器支持 json 请求吗?如果不尝试contentType: "application/x-www-form-urlencoded",请尝试data: {credentials: JSON.stringify(credentials)}
  • 据我所知,服务器支持 json 请求(我们将其用于另一个请求)。但我仍然尝试了你的选择,它也没有工作
  • 您有错误信息吗?因为那个请求很好,它可能是别的东西,你确定凭证是有效的吗?

标签: ajax post http-status-code-400 postdata


【解决方案1】:

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


    // credentials is an object
    var credentials = 
              {user_name: "test",
                password: "test"
              };
          alert(credentials);
          $.ajax({
              // check this url seems a bit off
              url:"../rest/user/login",
              type:"POST",
              // here we stringify the credentials only
              data:{credentials: JSON.stringify(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 +")");
              }
            }
    
          });

【讨论】:

    猜你喜欢
    • 2014-02-07
    • 2011-09-19
    • 2019-09-05
    • 2011-11-11
    • 2015-06-14
    • 2016-11-11
    • 1970-01-01
    相关资源
    最近更新 更多