2013-07-17 106 views
0


說,如果我有一個函數內這個jQuery AJAX調用:如何從AJAX調用中拋出異常並退出函數?

function callPageMethod(methodName, parameters) { 
    var pagePath = window.location.href; 

    $.ajax({ 
     type: "POST", 
     url: pagePath + "/" + methodName, 
     contentType: "application/json; charset=utf-8", 
     data: parameters, 
     dataType: "json", 
     success: function (response) { 
      alert("ajax successful!"); 
     }, 
     error: function (response) { 

      // this line is not working! 
      throw response.responseText; 
     } 
    }); 
} // end of function 


...我在Visual Studio 2010中收到此錯誤:

Microsoft JScript runtime error: Exception thrown and not caught


看來,如果這個問題不涉及到Visual Studio雖然,而是特別的JavaScript。

例如,我可以在$.ajax調用之前這個函數聲明一個變量,它分配在error:,然後throw它的功能$.ajax通話沒有問題後...



那麼我怎樣才能以這種方式拋出嵌套函數的錯誤?如果可能,我想catch這個函數以外的錯誤。

+0

您將無法抓住它的功能之外 - 阿賈克斯是異步的。只需返回ajax調用的結果(一個jQuery延遲對象),並利用jQuery的延遲方法 – Ian

+0

有時,來自_XMLHttpRequest_的安全錯誤將會忽略該請求/周圍代碼中的錯誤處理程序。 –

回答

0


因此,這裏有這個我已經發現了一些可能的解決方案:


      1 - 分配與error值的變量,並且 $.ajax電話後把它:

function callPageMethod(methodName, parameters) { 
    var errorValue = null; 

    $.ajax({ 
     ... 
     ... 
     ... 
     error: function (response) { 
      errorValue = response.responseText; 
     } 
    }); 

    if (errorValue != null) { 
     throw errorValue; 
    } 
} 


      2 - 使$.ajax呼叫同步

function callPageMethod(methodName, parameters) { 
    var errorValue = null; 

    $.ajax({ 
     ... 
     ... 
     ... 
     async: false, 
     error: function (response) { 

      // now it works: 
      throw response.responseText; 
     } 
    }); 
}