jQuery.ajax返回400 Bad Request

时间:2010-11-11 16:58:20

标签: ajax jquery

这很好用:

jQuery('#my_get_related_keywords').click(function() {
    if (jQuery('#my_keyword').val() == '') return false;
        jQuery.getJSON("http://boss.yahooapis.com/ysearch/web/v1/"
        +jQuery('#my_keyword').val()+"?"
        +"appid=myAppID"
        +"&lang=en"
        +"&format=json"
        +"&count=50"
        +"&view=keyterms"
        +"&callback=?",
        function (data) {//do something}

这将返回400 Bad Request(仅使用.ajax重新编写上述jQuery以支持错误处理)。

jQuery('#my_get_related_keywords').click(function()
    {
    if (jQuery('#my_keyword').val() == '') return false; 
    jQuery('#my_loader').show();
    jQuery.ajax(
        {
        url: "http://boss.yahooapis.com/ysearch/web/v1/"
        +jQuery('#my_keyword').val()+"?"
        +"appid=myAppID"
        +"&lang=en"
        +"&format=json"
        +"&count=50"
        +"&view=keyterms"
        +"&callback=?", 
        success: function(data)
            {//do something}

5 个答案:

答案 0 :(得分:18)

我认为您只需添加2个选项(contentTypedataType):

$('#my_get_related_keywords').click(function() {

    $.ajax({
            type: "POST",
            url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
            data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
            contentType: "application/json; charset=utf-8", // this
            dataType: "json", // and this
            success: function (msg) {
               //do something
            },
            error: function (errormessage) {
                //do something else
            }
        });
}

答案 1 :(得分:11)

将此添加到您的ajax调用:

contentType: "application/json; charset=utf-8",
dataType: "json"

答案 2 :(得分:7)

迟到的答案,但我认为值得保持更新。扩展Andrea Turri的答案以反映更新的jQuery API和.success / .error已弃用的方法。

从jQuery 1.8。*开始,首选的方法是使用.done()和.fail()。 Jquery Docs

e.g。

$('#my_get_related_keywords').click(function() {

    var ajaxRequest = $.ajax({
        type: "POST",
        url: "HERE PUT THE PATH OF YOUR SERVICE OR PAGE",
        data: '{"HERE YOU CAN PUT DATA TO PASS AT THE SERVICE"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json"});

    //When the request successfully finished, execute passed in function
    ajaxRequest.done(function(msg){
           //do something
    });

    //When the request failed, execute the passed in function
    ajaxRequest.fail(function(jqXHR, status){
        //do something else
    });
});

答案 3 :(得分:0)

例如,请确保在您的$ .ajax调用中始终使用“获取”或“发布”。

$.ajax({
    type: 'get',

必须遇到

  

app.get('/',function(req,res){

================ 还有帖子

$.ajax({
    type: 'post',

必须遇到

app.post('/', function(req, res) {

答案 4 :(得分:0)

即使设置后,我仍然收到400 Bad Request错误:

contentType: "application/json",
dataType: "json"

问题出在json对象中传递的属性类型,对于ajax请求对象中的data属性。
为了找出问题所在,我添加了一个错误处理程序,然后将错误记录到控制台。控制台日志将清楚地显示属性的验证错误。

这是我的初始代码:

var data = {
    "TestId": testId,
    "PlayerId": parseInt(playerId),
    "Result": result
};

var url = document.location.protocol + "//" + document.location.host + "/api/tests"
$.ajax({
    url: url,
    method: "POST",
    contentType: "application/json",
    data: JSON.stringify(data), // issue with a property type in the data object
    dataType: "json",
    error: function (e) {
        console.log(e); // logging the error object to console
    },
    success: function () {
        console.log('Success saving test result');
    }
});

现在,发出请求后,我检查了浏览器开发工具中的控制台选项卡。
它看起来像这样: enter image description here

responseJSON.errors[0]清楚地显示验证错误: JSON值无法转换为System.String。路径:$ .TestId ,这意味着在发出请求之前,我必须将TestId转换为数据对象中的字符串。

像下面那样更改数据对象的创建对我来说已经解决了这个问题:

var data = {
        "TestId": String(testId), //converting testId to a string
        "PlayerId": parseInt(playerId),
        "Result": result
};

我认为也可以通过记录和检查错误对象来识别其他可能的错误。