2012-12-04 21 views
2

我有一個Web服務,我從中收到XML響應。 jQuery中我有以下的,爲獲得某本書:顯示從服務器收到的div中的XML錯誤

function getBookByIsbn() { 

if($("#getAndDeleteIsbn").val() == '') 
{ 
    alert("Please provide the ISBN"); 
    return false; 
} 
$.ajax({ 
    dataType: 'xml', 
    type: 'GET', 
    url: 'http://localhost:8080/library/books/' + $("#getAndDeleteIsbn").val(), 
    success: function (data) { 
     var string; 
     if (window.ActiveXObject){ 
      string = data.xml; 
     } 
     else 
     { 
      string = (new XMLSerializer()).serializeToString(data); 
     } 
      $("#messageBox").text(string); 
    }, 
    error: function (xhr, status, thrownError) { 
     var string; 
     if (window.ActiveXObject){ 
      string = thrownError.xml; 
     } 
     else 
     { 
      string = (new XMLSerializer()).serializeToString(thrownError); 

     } 
      $("#messageBox").text(string); 
    } 
}); 
} 

現在,當請求成功,顯示該消息,但是當我收到一個錯誤,將不被顯示的內容。我究竟做錯了什麼?

編輯:有人建議我打印控制檯中的所有三個參數,所以我發現實際上xhr參數包含我需要的東西。 現在的問題是,如果我嘗試創建警報(xhr.responseText),警報窗口包含所需的消息,但如果我想在div內顯示相同的內容,則不會發生任何事情,並且我希望顯示它那裏。

+0

是什麼錯誤???? –

+0

「錯誤的文本」當出現錯誤時,在服務器端,我把含有一些XML自定義異常,我想顯示XML例如,如果用戶引入的ISBN包含字母,我將收到400 Bad Request ISBN只能包含數字! ...我確實在控制檯收到了這條消息 –

回答

2

問題是我嘗試將字符串序列化爲字符串,因爲xhr.responseText是一個字符串。爲了解決這個問題,而不是xhr.responseText,它應該是xhr.responseXML。 下面是代碼:

function getBookByIsbn() { 


if($("#getAndDeleteIsbn").val() == '') 
{ 
    alert("Please provide the ISBN"); 
    return false; 
} 
$.ajax({ 
    dataType: 'xml', 
    type: 'GET', 
    url: 'http://localhost:8080/library/books/' + $("#getAndDeleteIsbn").val(), 
    success: function (data) { 
     var string; 
     if (window.ActiveXObject){ 
      string = data.xml; 
     } 
     else 
     { 
      string = (new XMLSerializer()).serializeToString(data); 
     } 
      $("#messageBox").text(string); 
    }, 
    error: function (xhr, status, thrownError) { 
     var string; 
     if (window.ActiveXObject){ 
      string = xhr.responseXML.xml; 
     } 
     else 
     { 
      string = (new XMLSerializer()).serializeToString(xhr.responseXML); 

     } 
      $("#messageBox").text(string); 
    } 
}); 
} 
0

服務器和獲得服務器的響應我也得到同樣的事情。你只需要檢查它的錯誤或響應。爲此,你可以使用JavaScript的xquery或得到使用。

//suppose you get response in variable 'xml_response'. 
var res = xml_response.getElementByTagName('errorMessage'); 
//if result exist then it is error other wise it is not error. 
if (res[0]){ 
    alert ('error occur on server side. '); 
    return; 
}else{ 
//show you record in div. 
} 
相關問題