jQuery 1.9 introduces a stricter policy by which the selector engine handles HTML strings. In short, an HTML string is considered to be well-formed only if it starts with a less-than symbol (<
). This policy also affects the way HTML strings are handled by AJAX methods.
We have a simple page switcher which makes use of a select box. Each option's value loads a different page. The third page is ill-formed because it starts with a >
character followed by normal markup.
If we use the .html()
method, everything apparently works fine:
(function($) {
$(function() {
$('#post').on('change', function() {
var $select = $(this),
value = $('option:selected', $select).val();
$.post('post.php', { number: value }, function(page) {
$('#output').html(page); // This works
});
});
});
})(jQuery);
But if we pass the returned HTML string to the selector engine:
(function($) {
$(function() {
$('#post').on('change', function() {
var $select = $(this),
value = $('option:selected', $select).val();
$.post('post.php', { number: value }, function(page) {
$('#output').empty();
$(page).appendTo('#output'); // Error!
});
});
});
})(jQuery);
we got an error when we choose the third page because the HTML string is ill-formed. You can see a test in the following video.