【问题标题】:jQuery .load() method not working w/ CMS articlesjQuery .load() 方法不适用于/CMS 文章
【发布时间】:2011-10-17 23:20:26
【问题描述】:

我正在构建一个小部件,当用户将鼠标悬停在特定菜单选项上时,它会显示来自网站不同部分 (Joomla) 的信息。根据我看到的行为,在我看来,这种方法不适用于 CMS 文章之类的东西,因为我一直收到一个空的(请参阅:http://cl.ly/1k3n151n3o0d1f2A1e3k)响应。

下面的代码运行良好,并且在我引用静态文件时完全符合我的要求:

<!DOCTYPE html>
<html>
<!--[if lt IE 7 ]> <html lang="en" class="no-js ie6"> <![endif]-->
<!--[if IE 7 ]>    <html lang="en" class="no-js ie7"> <![endif]-->
<!--[if IE 8 ]>    <html lang="en" class="no-js ie8"> <![endif]-->
<!--[if IE 9 ]>    <html lang="en" class="no-js ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html lang="en" class="no-js"> <!--<![endif]-->
<head>
  <meta charset="UTF-8">

  <title>Div/Scraping Testing</title>
  <meta name="description" content="">
  <meta name="author" content="">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
  <script src="http://scripts.dri.edu/Other/modernizr.js"></script>
  <script type="text/javascript">
  $(document).ready(function()
  {
    $("#wifi").mouseover(function()
    {
      $("#show").load('wifi.php #wifi');
      $("#show").show();
    });
    $("#wifi").mouseout(function()
    {
      $("#show").hide();
    })
  });

  </script>

</head>
<body>
  <div id="container">
    <header>

    </header>

    <div id="main" role="main">
      <div id="nav">
        <center>
          <a href="wireless.php" id="wifi">WiFi</a> || <a href="#">Test</a>
        </center>
      </div>
      <div id="show" style="display:none;">
        <center><h3>Wireless Info.</h3></center>
      </div>
    </div>

    <footer>
    </footer>
  </div>
</body>
</html>

正如您所期望的那样,带有 ID="wifi" 的 div 中的数据显示在我的“show” div 中。当我将 JavaScript 更改为以下内容时:

  $("#show").load('http://cmsurl.com/is/is-network-access/22-wireless-access/ #wifi');

我从上面链接到的图片中得到空响应。这只是 .load() 方法的一个限制,因为它无法解析 CMS 文章中的数据并需要静态文件,还是我只是以错误的方式处理事情?

【问题讨论】:

  • 您正在运行的页面是否在 cmsurl.com 域上?如果不是,这将不起作用,因为 XHR 无法跨域执行。您需要使用 JSONP。简单解释:developer.mozilla.org/en/Same_origin_policy_for_JavaScript.
  • SoWeLie:实际上是在另一个域上导致了问题。一旦我将脚本移动到同一个域,一切都按预期工作。

标签: javascript jquery content-management-system cross-domain


【解决方案1】:

您遇到了Same Origin Policy 施加的限制。简而言之,禁止对不同域的 AJAX 调用,并且总是会失败。

您需要使用 JSONP(主要适用于 API 返回的数据)或proxy the request through your own server/domain

【讨论】:

  • 轰隆隆!你说得对,我将文件从我的测试区域移动到生产环境(它与我传递给 .load() 方法的 URL 位于同一个域中),我很高兴。感谢您的信息!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-09
  • 2012-12-11
  • 1970-01-01
  • 2015-11-02
相关资源
最近更新 更多