weixin_33671935 2014-09-18 07:02 采纳率: 0%
浏览 9

jQuery.Ajax错误结果

Im using MVC on server side and calling a function via jQuery.Ajax sending json type. the function results with exception. i want to invoke/trigger the error result function of the Ajax, what should i send back with the return JSON function? for the example, let's say the return JSON is triggered from the catch section.

MVC Function

public JsonResult Func()
{       
    try
    {               
        var a = 0;
        return Json(a, JsonRequestBehavior.AllowGet);              
    }
    catch (Exception ex)
    {
        FxException.CatchAndDump(ex);
        return Json(" ", JsonRequestBehavior.AllowGet);
    }
}

JavasScript call

$.ajax({
    url: '../Func',
    type: 'GET',
    traditional: true,
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (data) {
        alert('s');
    },
    error: function (data) {
        alert('e');
    }
});
  • 写回答

3条回答 默认 最新

  • weixin_33739523 2014-09-18 07:08
    关注

    Quoting from this answer:

    The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:

    HTTP 404/500 or any other HTTP error message has been received data of incorrect type was received (i.e. you have expected JSON, you have received something else).

    The error callback will be executed when the response from the server is not going to be what you were expecting. So for example in this situations it:

    HTTP 404/500 or any other HTTP error message has been received data of incorrect type was received (i.e. you have expected JSON, you have received something else). In your situation the data is correct (it's a JSON message). If you want to manually trigger the error callback based on the value of the received data you can do so quite simple. Just change the anonymous callback for error to named function.

    function handleError(xhr, status, error){
    
        //Handle failure here
    
     }
    
    $.ajax({
    
      url: url,
      type: 'GET',
      async: true,
      dataType: 'json',
      data: data,
    
     success: function(data) {
         if (whatever) {
             handleError(xhr, status, ''); // manually trigger callback
         }
         //Handle server response here
    
      },
    
     error: handleError
    });
    
    评论

报告相同问题?