2014-12-07 101 views
0

我的AJAX返回一個包含在<div class = 'Post'>....</div>中的HTML或僅包含No new data yet的HTML。AJAX過濾器()和find()在AJAX響應中返回錯誤

var request = $.ajax({ 
    url: "/mysite/load_latest/", 
    type: "POST", 
    data: { user_id : userID }, 
    dataType: "html" 
}); 
request.done(function(msg){ 
    console.log(msg); 
    var class1 = $(msg).filter(".Post"); 
    console.log(class1);    
}); 

我要檢查,如果在返回的HTML存在.Post但它返回此錯誤:Uncaught Error: Syntax error, unrecognized expression: <div class = 'Post'>...content...</div>

我試圖$(msg).find(".Post");但它返回相同的錯誤。

+0

msg應該返回什麼? – 2014-12-07 03:52:15

+0

@ Mohamed-Yousef:HTML:'

content goes here
' – Yax 2014-12-07 04:03:22

+0

它還沒有html ..它只是字符串,直到你將它顯示爲html – 2014-12-07 04:07:56

回答

1

設法使一個新的元素,附加,你的反應,然後搜索所需元素:

request.done(function(msg) { 
    var element = 
     // make a new element on the fly 
     $('<div></div>') 

     // put the `msg` response inside it 
     .html(msg) 

     // now search for `.Post` element 
     .find('.Post') 
    ; 

    // the length will be `0` or more 
    alert(element.length); 
}); 
+0

這樣做了,但我圍繞'

...
'包裹了另一個'div',它給了我想要的東西。你的也是。區別在於:我在後端完成,在前端完成。這是否有其他優勢? – Yax 2014-12-07 04:35:19

+0

沒有區別,他們都沒問題。但是我會選擇前端方式,這樣可以避免不必要的錯誤(如果服務器沒有正確包裝代碼)。 – dashtinejad 2014-12-07 04:42:39

0
在你的代碼

例如HTML

<div class="msg_html"></div> 

request.done(function(msg){ 
    $('.msg_html').html(msg); 
    $('.Post').css('background','yellow'); 
    alert('Now your Post class has a background yellow if its a content in it');   
}); 
+1

您應該在元素內搜索,而不是整個文檔。此外,將響應附加到真正的HTML標籤並不是一個好主意。 – dashtinejad 2014-12-07 04:31:09

+0

對不起,但你的答案是遠離我的問題尋求。 – Yax 2014-12-07 04:36:42