简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM