2015-06-28 134 views
0

我想用AJAX使用我發現的方法加載頁面hereAJAX解析HTML返回[對象對象]

一切順利,直到我找到parse_html函數。下一個網頁上的元素的正確值將分配給body變量(即body標籤中的一段HTML代碼)。但是當它變成jQuery對象時,$body最終等於Object(我認爲這可能是正確的?我認爲這是一個DOM對象,它具有來自body標籤的所有HTML)。

最後,使jQuery對象「$ content」等於第一個「#content」元素的內容。但是,響應。$ content最終等於「[object Object]」。

我該怎麼做才能讓我在使用$ content.html(response. $ content)時#content div是用來自新頁面而不是[object Object]的HTML填充的。

function find_all($html, selector) { 
    return $html.filter(selector).add($html.find(selector)); 
} 

function parse_html(html) { 
    return $($.parseHTML(html, document, true)); 
} 

// Convert page contents to jQuery objects 
function parse_response(html) { 

    // 'body' is equal to the strings of text in between the body tags 
    var body = /<body[^>]*>([\s\S]+)<\/body>/.exec(html), 

    $body = body ? parse_html(body[1]) : $(), 

    // '$content' is equal to the contents of the first #content element 
    $content = $.trim(find_all($body, '#content').first().contents()); 

    // Output the variable "$content" 
    return { 
    '$content': $content 
    } 
} 

爲背景,這裏是我調用這些函數內聯:

url = History.getState().url, 
rel = url.replace(root, "/"); 
$.get(rel).done(function (data) { 

    var response = parse_response(data); 

    var $content = $("#content"); 

    $content 
     .slideUp(500) // Get it off screen to start 
     .promise() 
     .done(function() { 
      $content 
       .html(response.$content) 
       .slideDown(500); 
     }); 
}).fail(function() { 
      document.location.href = url; 
      return false; 
}); 
+0

爲什麼要解析響應? jQuery根據內容類型默認做到這一點。所以你正試圖解析DOM? – epascarello

+0

我可能在這裏是錯的,但我想在parse_response裏面發生了什麼,爲了找到第一個#content元素,它需要將HTML分隔成DOM值而不是一個長字符串(我的詞彙表可能在這裏是錯誤的)。這樣它可以挑出#content元素並將其分配給$ content對象。 –

回答

0

的問題是你不調用轉換爲內容的字符串。在這樣的parse_response中添加對html()函數的調用

function parse_response(html) { 

    // 'body' is equal to the strings of text in between the body tags 
    var body = /<body[^>]*>([\s\S]+)<\/body>/.exec(html), 

    $body = body ? parse_html(body[1]) : $(), 

    // '$content' is equal to the contents of the first #content element 
    $content = $.trim(find_all($body, '#content').first().contents().html()); 

    // Output the variable "$content" 
    return { 
    '$content': $content 
    } 
} 
+0

這確實完全相同(只插入文本而不是新頁面中的html元素)。但是你讓我意識到我可以添加一個叫.html()函數而不是文本。儘管如此,我希望這不會讓整個考驗成爲多餘。 –

+0

啊,好的,我會更新我的答案 –