2017-07-24 67 views
0

使用JavaScript/Jquery/jqGrid在C#ASP.NET項目中工作。Ajax能否成功()處理兩種類型的返回?

新的任務是讓頁面i)接受Excel輸入文件,ii)使用列ID查找附加信息,iii)使用輸入文件中的一些列和所有返回的列生成新的Excel文件從數據庫。

我已經完成了,但只是想做更多的錯誤處理。在存儲過程中,如果一切正常,它會返回一個數據表(或在Oracle術語中,CURSOR)。如果出現錯誤,我添加了一個catch塊並返回一條錯誤消息。

我修改了AJAX調用。除數據類型添加爲「文本」,我期望返回爲XML。

$.ajax({ 
    // POST 
    // URL: url to call that stored procedure 
    dataType: text, 
    success: function (response) { 
     // now the response is XML (don't know why... 
     // specify dataType as 'text', but get XML...) 
     // If response contains 'string' tag, report error. 
    }, 
    failure: ... 
}) 

這是我以前做的事。我沒有指定數據類型,但以某種方式工作。

$.ajax({ 
    // POST 
    // ... rest is same but without the dataType 
    success: function (response) { 
     Download(response) 
     // The file is already and placed in Download directory. 
     // Call 'Download()' will actually make the download happen 
     // But here response is just a path to the Download directory + 
     // download file name. 

和下載()是:

function Download(url) { 
    document.getElementById('my_iframe').src = <%=ResolveUrl("~/")%> +url; 
    return false 
}; 

怎樣纔可以有成功的功能處理這兩種類型的反應呢? (僅供參考:前端頁面是ASP.NET,按鈕點擊會調用JavaScript函數,該函數通過$ .ajax()調用web服務函數,因爲有很多行,web服務功能調用數據庫中的類很多次函數 - 每一次傳中只有一個ID的功能將在返回調用存儲過程)


編輯:感謝您從穆斯塔法Larhrouch解決方案。以下是我必須調整的幾點:

  1. 添加數據類型。
  2. 如果響應是XML,請檢查是否有錯誤。
  3. 如果不是XML,只需下載。

這裏是我的代碼:

$.ajax({ 
    // POST 
    // URL 
    dataType: "text", 
    success: function (response) { 
     if (isXML(response)) { 
      var xmlDoc = $.parseXML(response); 
      $xml = $(xmlDoc); 
      var errMsg = $xml.find("string").text(); 

      if (errMsg != "") { 
       // pop up a dialog box showing errMsg 
      } 
     } 
     else { 
      Download(response); 
     } 

回答

2

您可以檢查是否響應是XML,如果它是分析它,如果沒有響應是一個字符串。您可以使用此功能來檢查響應是否爲xml:

function isXML(xml){ 
    try { 
     xmlDoc = $.parseXML(xml); //is valid XML 
     return true; 
    } catch (err) { 
     // was not XML 
     return false; 
    } 
} 


$.ajax({ 
    // POST 
    // ... rest is same but without the dataType 
    success: function (response) { 
     if(isXML(response){ 
      Download(response) 
     } 
     else{ 
      //report as error 
     } 
+0

謝謝。你指向正確的方向。對於那些正在閱讀本文的人,請參閱我的問題的編輯部分。有幾點我必須補充。 – user3454439