Why does this jQuery fail to load/parse my HTML string?

孤人 提交于 2019-12-24 18:43:41

问题


jQuery.get(window.location.href, function(data) {
  alert(data);
  alert($(data).html());
});

The first popup is all the HTML good and healthy.

The second popup is blank. Why? (the HTML is XHTML compliant)


回答1:


From the documentation:

The HTML string cannot contain elements that are invalid within a div, such as html, head, body, or title elements.

If you are fetching a complete HTML document, then you will have lots of elements that may not appear in a div.




回答2:


Because it will return a string with all the HTML. data isn't a jQuery object.




回答3:


I tried this on my PC. You get back the following:

"

<!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 id="Head1"><title>

</title><link href="App_Themes/selectors.css" rel="stylesheet" type="text/css" /></head>................etc

This will not parse into a jQuery obejct. You get needs to be on a server-side script page that will explicitly output HTML.

I suppose if you really need an item in the HTML then you can strip it out from the text using the built-in string methods.




回答4:


Change your code to something like this

$('#yourContainingDiv').html(data);

The html in data will be placed in the div tag



来源:https://stackoverflow.com/questions/1444030/why-does-this-jquery-fail-to-load-parse-my-html-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!