¿Por qué no puedo poner la página HTML devuelta por $ .ajax en el contenedor jQuery?

The HTML returned in the $.ajax success callback doesn't let me put it in a jQuery wrapper and apply standard jQuery methods to it. Why is this? For example, this alerts null:

dataType: "html",
success: function(myHTML) {
   var $myHTML = $(myHTML);
   alert( $myHTML.html() ); // returns null
}

My intention is to modify the myHTML using jQuery methods (this is why I need to put it in the jQuery wrapper), and then return the modified html (full, including <head>, scripts, etc.) as a string. But none of the jQuery methods I try work on $(myHTML). How come?

A working version of the code is here: http://jsfiddle.net/supertrue/Uw5dc/

var getHTML = function ( url ){        

        $.ajax({
                  url: url,
                  dataType: "html",
                  success: function( myHTML ) {

                      // view the returned HTML
                      alert('Successfully grabbed this HTML: \n\n' + myHTML);

                      // the opening <html> tag is missing (no idea why)
                      myHTML.replace('<head>', '<html><head>');

                      // put it in a jQuery wrapper
                      var $myHTML = $(myHTML);

                      // use jQuery to manipulate it
                      // $myHTML.find('script').remove(); // just an example

                      // then view the final html
                      alert('$myHTML.html(): \n\n' + $myHTML.html()); // doesn't work!

                      // that didn't work; try getting outerHTML
                      $myHTML = $('<div></div>').append(myHTML);
                      alert('$myHTML.html(): \n\n' + $myHTML.html()); // highly incomplete! missing scripts and <head>, <body> wrappers    

                  }
              });

     }

preguntado el 01 de febrero de 12 a las 04:02

1 Respuestas

Mira la documentación de jQuery Método aquí (scroll down to the part for jQuery(html[, ownerDocument])), it says this:

When passing in complex HTML, some browsers may not generate a DOM that exactly replicates the HTML source provided. As mentioned, we use the browser's .innerHTML property to parse the passed HTML and insert it into the current document. During this process, some browsers filter out certain elements such as <html>, <title>, or <head> elements. As a result, the elements inserted may not be representative of the original string passed.

Given this, it's unlikely you are going to be able to generate the whole page (i.e. including <html> and tags like that) using $(html), only parts that are compatible with how it works (e.g. tags that you would normally use within <body> should probably work OK).

Respondido 01 Feb 12, 08:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.