jQuery load()函数不会加载远程页面,但在文本编辑器中以预览模式工作。

时间:2012-05-28 10:31:06

标签: ajax jquery

基本上,当用户点击链接时,我正在尝试获取远程内容。

它适用于Coda HTML预览窗口,但是当我在真实浏览器(Chrome / FF / Safari)中测试html时,它将无法正常工作,将无法获取远程内容。 (我确定jquery正在工作,因为警报('url是'+ url);当我点击链接时会弹出

有线。怎么了?

enter image description here

enter image description here

我的代码如下

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Sample</title>

  <link type="text/css" href="http://localhost/jquery-ui-1.8.20.custom/css/smoothness/jquery-ui-1.8.20.custom.css" rel="stylesheet" />
  <script type="text/javascript" src="http://localhost/jquery-ui-1.8.20.custom/js/jquery-1.7.2.min.js"></script>
  <script type="text/javascript" src="http://localhost/jquery-ui-1.8.20.custom/js/jquery-ui-1.8.20.custom.min.js"></script>

  <script type="text/javascript">
    $(document).ready(function() {
        $('#links a').click(function(e) {
            var url = $(this).attr('href');
                    alert('url is ' + url);  
            $('#content').load(url);
            e.preventDefault();
        });
    });  // document ready
  </script>

</head>

<body>

<ul id="links">
  <li><a href="http://google.com">Google</a></li>
  <li><a href="http://yahoo.com">Yahoo</a></li>

</ul>
<div id="content"></div>

</body>
</html>

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

这是因为Same Origin Policy。这是大多数浏览器的安全功能。最常见的解决方法是使用JSONP,但由于您希望将HTML作为响应,因此这对您无效。

您需要使用的是服务器端代理,您可以在PHP / ASP.Net /其他服务器端技术中发出请求以获取URL的HTML,然后通过本地请求将其公开给您的jQuery