How to trigger jquery.ajax() error callback based on server response, not HTTP 500?

后端 未结 6 1147
清酒与你
清酒与你 2020-11-30 03:32

By using jquery ajax function, I can do something like:

$.ajax({

  url: url,
  type: \'GET\',
  async: true,
  dataType: \'json\',
  data: data,

 success:          


        
6条回答
  •  天命终不由人
    2020-11-30 04:15

    We presume the server is sending JSON, and in case of a successful request we'll get something like this:

    {
        success: true,
        data: {
            name: 'Foo'
        }
    }
    

    ... and on failure:

    {
        success: false,
        error: 'Something bad happened.'
    }
    

    Then we simply filter the response with a $.Deferred:

    $.get('http://localhost/api').then(function(res) {
        var filter = $.Deferred();
    
        if (res.success) {
            filter.resolve(res.data);
        } else {
            filter.reject(res.error);
        }
    
        return filter.promise();
    }).done(function(data) {
        console.log('Name:',  data.name); // Outputs: Foo
    }).fail(function(error) {
        console.log('Error:', error); // Outputs: Something bad happened.
    })
    

提交回复
热议问题