Reputation: 12423
Could someone tell me if this:
$.ajax({
url: 'test.html',
success: function(data) {
alert("Data Loaded: " + data);
}
});
is the same as this:
$.ajax({
url: 'test.html',
success: function(data) {
alert("Data Loaded: " + $(data).html());
}
});
When retrieving this content:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>blank page</title>
</head>
<body>
<div id="content">Some content.</div>
</body>
</html>
I ask because the second jquery ajax call does not alert. Could someone explain why the two versions of the alerts are not the same please?
Upvotes: 1
Views: 126
Reputation: 5303
The second example isn't calling alert
because an error is occurring inside of the success
callback. Switch firebug on and you should see that an error is happening (though the line that firebug tells you it's occurring on won't be accurate). If for some reason firebug doesn't show you an error is happening, it's because jQuery is gracefully handling exceptions from the functions assigned to success
. You could wrap your alert
with a try/catch block and see for yourself.
$.ajax({
url: 'test.html',
success: function(data) {
try {
alert("Data Loaded: " + $(data).html());
} catch (e) {
alert("Error happened: " + e.message);
}
}
});
That error is happening because the data being returned isn't an actual HTML element.
Upvotes: 0
Reputation: 20357
Because the doctype is XHTML, the first example is returning XML. So, when you alert the XML it is correct. In the second example, jQuery must think it's XML, which can't be accessed with .html().
To get the second example to work try the option
dataType: "html"
Upvotes: 1
Reputation: 10570
Quoting the jQuery Documentation for the $-function:
Simple elements without attributes, e.g., "", are created via document.createElement. All other cases are parsed by assigning the string to the .innerHTML property of a div element. The HTML string cannot contain elements that are invalid within a div, such as html, head, body, or title elements.
You cannot put a full html-page into the $-function, only elements that are valid in a div
-element.
Upvotes: 2