jQuery.ajax returns 400 Bad Request

前端 未结 5 1634
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 10:06

This works fine:

jQuery(\'#my_get_related_keywords\').click(function() {
    if (jQuery(\'#my_keyword\').val() == \'\') return false;
        jQuery.getJSON(         


        
相关标签:
5条回答
  • 2020-12-09 10:19

    Late answer, but I figured it's worth keeping this updated. Expanding on Andrea Turri answer to reflect updated jQuery API and .success/.error deprecated methods.

    As of jQuery 1.8.* the preferred way of doing this is to use .done() and .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
        });
    });
    
    0 讨论(0)
  • Be sure and use 'get' or 'post' consistantly with your $.ajax call for example.

    $.ajax({
        type: 'get',
    

    must be met with

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

    =============== and for post

    $.ajax({
        type: 'post',
    

    must be met with

    app.post('/', function(req, res) {
    
    0 讨论(0)
  • 2020-12-09 10:25

    I was getting the 400 Bad Request error, even after setting:

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

    The issue was with the type of a property passed in the json object, for the data property in the ajax request object.
    To figure out the issue, I added an error handler and then logged the error to the console. Console log will clearly show validation errors for the properties if any.

    This was my initial code:

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

    Now after making the request, I checked the console tab in the browser development tool.
    It looked like this:

    responseJSON.errors[0] clearly shows a validation error: The JSON value could not be converted to System.String. Path: $.TestId, which means I have to convert TestId to a string in the data object, before making the request.

    Changing the data object creation like below fixed the issue for me:

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

    I assume other possible errors could also be identified by logging and inspecting the error object.

    0 讨论(0)
  • 2020-12-09 10:33

    Add this to your ajax call:

    contentType: "application/json; charset=utf-8",
    dataType: "json"
    
    0 讨论(0)
  • 2020-12-09 10:40

    I think you just need to add 2 more options (contentType and dataType):

    $('#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
                }
            });
    }
    
    0 讨论(0)
提交回复
热议问题