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

后端 未结 6 1145
清酒与你
清酒与你 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条回答
  •  -上瘾入骨i
    2020-11-30 04:28

    Simplest thing to do would be to restructure like so:

    function handleAjaxError function(xhr, status, error) {
        //Handle failure here
    }
    
    $.ajax({
      url: url,
      type: 'GET',
      async: true,
      dataType: 'json',
      data: data,
    
      success: function(data) {
    
         //Handle server response here
        if (data.message == 'There is an error')
        {
            handleAjaxError();
            return;
        }
    
        //... all is good....
    
      },
      error: handleAjaxError
    });
    

提交回复
热议问题