【问题标题】:jQuery.ajax returns 400 Bad RequestjQuery.ajax 返回 400 错误请求
【发布时间】:2010-11-11 16:58:20
【问题描述】:

这很好用:

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}

【问题讨论】:

  • 你必须在某处添加方法(post 或 get)吗?

标签: ajax jquery


【解决方案1】:

我认为您只需要再添加 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
            }
        });
}

【讨论】:

    【解决方案2】:

    将此添加到您的 ajax 调用中:

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

    【讨论】:

    • 谢谢。就是这样。 @Toro 刚刚打败了你 :)
    【解决方案3】:

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

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

    例如

    $('#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
        });
    });
    

    【讨论】:

      【解决方案4】:

      例如,请确保在 $.ajax 调用中始终使用“get”或“post”。

      $.ajax({
          type: 'get',
      

      必须满足

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

      =============== 和帖子

      $.ajax({
          type: 'post',
      

      必须满足

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

      【讨论】:

        【解决方案5】:

        我收到 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');
            }
        });
        

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

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

        像下面这样更改数据对象的创建为我解决了这个问题:

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

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

        【讨论】:

          猜你喜欢
          • 2019-07-28
          • 2019-07-11
          • 2015-04-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多