JSON ajax发布数据 - 得到400条错误的请求消息

时间:2016-01-05 09:03:57

标签: javascript jquery json ajax

首先。我在stackoverflow中读到了很多关于这个问题的问题,但没有任何帮助。

我有这个功能:

function ip_login(){
    //alert(JSON.stringify(arr_login));
    $.ajax({
        crossdomain: true,
        url: 'https://****/Token',
        type: 'POST',
        data: JSON.stringify(arr_login),   
        contentType: 'application/x-www-form-urlencoded',
        dataType: 'json',
        success: function (data) { 
            console.log(data);
        }
    });        
}

这是我的JSON字符串:

{"grant_type":"password","username":"mail@mail.de","password":"blabla"}

使用谷歌浏览器扩展程序“postman”,它可以正常工作!

如果我测试上面的代码,我会收到热门的400 bad request消息。

当我使用扩展名“postman”的代码时,它也不起作用。

这是邮递员的代码:

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://*****/Token",
  "method": "POST",
  "headers": {
    "cache-control": "no-cache",
    "content-type": "application/x-www-form-urlencoded"
  },
  "data": {
    "grant_type": "password",
    "username": "mail@mail.de",
    "password": "blabla"
  }
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

我不能解决我的问题..

我在谷歌搜索过,但没有回复帮助我。

编辑:

这是在我的控制台中:

“NetworkError:400错误请求 - https://awesome-url.de/Token

2 个答案:

答案 0 :(得分:2)

问题在于串联JSON。服务器期望json,但你发送字符串(字符串化JSON)。尝试

function ip_login(){
    //alert(JSON.stringify(arr_login));
    $.ajax({
        crossdomain: true,
        url: 'https://****/Token',
        type: 'POST',
        data: arr_login,   
        contentType: 'application/x-www-form-urlencoded',
        dataType: 'json',
        success: function (data) { 
            console.log(data);
        }
    });        
}

答案 1 :(得分:0)

不确定这是否有帮助,但无论如何都要尝试。 当我发送Json时,我没有使用“JSON.stringify(arr_login)” 我所做的只是“数据:{arr_login:arr_login}”

这就是我的变量的样子。

var req = new Object();
req["type"] = 'refresh';
req["time"] = window.page_ordertime;

这就是我的ajax的样子

$.ajax( {
    url:"listorder_process.php",
    method: "POST",
    dataType:"json",
    data:{request:req}
} )
相关问题