将外部页面的内容加载到div?

时间:2013-05-13 16:47:39

标签: javascript jquery

这是我的主页

<html>

<head>
  <title></title>
  <style>
  #exp{
    height: 100%;
    width:100%;
    position: absolute;
    left:0;
    top:0;
    background:#00FF00;
  }

  </style>
  <script src="scripts/jquery.js"></script>
  <script>
  $(function(){
  $("#exp").load('aboutus.html');

  })
  </script>

</head>

<body>
<div id="exp">

</div>
</body>

</html>

我想从aboutus.html页面加载此内容 该页面中的内容为

<div style="height:100%;width:100%;position:absolute;left:0px;top:0px">Hai</div>

我尝试加载,获取,.html等但它们都没有工作。 我不想包含php

我试过的方法

$("#exp").load('aboutus.html');
$("#exp").get('aboutus.html');
$("#exp").html(url(aboutus.html'));

2 个答案:

答案 0 :(得分:0)

失败的最常见原因是本地测试:如果使用file://打开主文件,则另一个文件似乎来自另一个域,并且操作被阻止。

来自the .load documentation

  

附加说明:

     

由于浏览器安全限制,大多数“Ajax”请求都是主题   同源政策;请求无法成功检索   来自不同域,子域或协议的数据。

您必须使用http服务器来测试此页面。

除此之外,假设你有jquery.js文件,你的代码就可以运行:test it online

答案 1 :(得分:0)

使用jquery使用AJAX调用来实现此目的的一种方法。

将您的about页面包装成JSON回调函数。详情见下文

主页代码

<html>
<head>
<title></title>
<style>
#exp {
height: 100%;
width:100%;
position: absolute;
left:0;
top:0;
background:#00FF00;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
jQuery(function(){
jQuery.getJSON('about.php?callback=?',function(data){
if(data.status == 'success') {
        jQuery('#exp').html(data.html);
    }
});
})
</script>
</head>
<body>
<div id="exp"> </div>
</body>
</html>

关于.PHP页面

<?php
$html .=<<<HTML
    <div style="height:100%;width:100%;position:absolute;left:0px;top:0px">Hai</div>
HTML;
$strippedHTML = str_replace(array("\r\n", "\r", "\n", "\t"), ' ', $html);
echo $_GET['callback'] . '({"status":"success", "html":"' . addslashes(trim($strippedHTML)) . '"})';
?>
相关问题