簡體   English   中英

ajax使responseText成為對象

[英]ajax make responseText to be an object

我需要獲取ajax答案作為DOM對象。

這是我的代碼:

$.ajax(URL, {
    async: false,
    complete: function(e){
        code = $(e.responseText);
        alert( code.find('body').length );
    }
});

因此,我需要將響應作為對象,然后在其中進行選擇。

但是在先前的示例中,我的Firebug返回了:

Object[<TextNode textContent="\n\n \n ">, title, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">

例如,此代碼可以正常工作:

$.get(URL, function(e){
    var code = $(e);
    alert( code.find('body').length );
});

但是我需要發出一個異步請求,因此$ .get不是一個選項(否則我無法找到解決方案)。

感謝您的指教!

您的ajax代碼不正確,應該是這樣,您可以在成功回調中獲取響應:

$.ajax({
   url:URL,
   type : "get", 
   dataType: "html", // expected output from the requested url
   success: function(e){
      code = $(e.responseText); // or try with $(e) only
      alert( code.find('body').length );
   }, 
   error: function(err){
      alert(err.responseText);
   }
});

我目前發現的唯一解決方案是將返回的數據制成html,然后便可以對其進行操作。 我的工作示例是:

$.ajax({
    url: URL,
    async: false,
    type : "get",
    dataType: "html",
    success: function(data){
        var response = $('<html/>').html(data);
        alert(response.find('#ELEM').length);
    }
});

因此,如您所見-我將響應數據制成HTML,這有助於我使用.find()和其他有用的東西。

希望此解決方案會有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM