English 中文(简体)
Ajax请求有效,但没有CSS
原标题:Ajax request works, but with no CSS

下面是我为Ajax请求准备的一段代码。请求有效,但当处理请求时,页面显示时没有任何CSS(即使我的所有内容都在同一目录中)。为了测试这一点,我将请求指向我网站上已经存在的一个页面。有什么帮助吗?提前谢谢。

<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>
问题回答

并非所有浏览器都支持通过Ajax在页面中注入css(无论是内联还是通过<;link>;标记)。

解决方案是为包含ajax调用的页面中的ajax内容加载CSS。

根据W3学校,样式表的<;link>;元素只能出现在文档中。

因此,如果您在<;div>那些将不会被加载。

问题是您正在用innerHTML覆盖H2标记。如果你有这样的东西

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

它将保留h2。或者您需要返回AJAX:

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

将css移动到<;样式>;使用ajax请求的pege中的元素。应该做到。

第二种方法是将您使用ajax请求的页面的css插入到您请求的witch页面的css文件中。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.