开发者

Ajax request works, but with no CSS

Below is a snippet of code I have for an Ajax request. The request works, but when the request is processed the page appears without any of the CSS (even though I have everything in the same directory). To test this I made the request point to开发者_运维百科 a page on my site that already existed. Any help? Thanks in advance.

<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {
  xmlhttp=new XMLHttpRequest();
  }
else
  {
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajaxtest.html",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>


Injecting css in a page via Ajax is not supported by all browsers (whether inline or via a <link> tag).

The solution is to load the CSS for the ajax content in the page containing the Ajax call.


According to W3 Schools, a <link> element for a stylesheet can only appear in your document <head>.

Hence if you include the contents of a whole external file (that links its own styles) within your <div> those won't be loaded.


The problem is that you are overwriting the H2 tag with the innerHTML. if you had something like

<h2 id="myDiv">Let AJAX change this text</h2>

It would keep the h2. Or you need to have the AJAX pass back:

<h2>What I want to change it to</h2>


Move your css inside a <style> element inside the pege you request with ajax. Should do the trick.

Second way is to insert the css for the page you request with ajax into the css file of the page from witch you request.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜