【问题标题】:Javascript is not loading when I load the content of external website当我加载外部网站的内容时,Javascript 没有加载
【发布时间】:2012-06-02 14:03:24
【问题描述】:

我有一个页面,我通过 Jquery Post 方法将外部网站内容加载到我的 PHP 文件(由于跨站点问题),看起来像这样。(back.php)

$url = $_POST['url'];
echo file_get_contents($url);

我的 HTML 代码如下所示

    $.post ("back.php",
    {
        url : "http://www.ralphlauren.com/product/index.jsp?productId=2130294&cp=1760781.1760809&ab=ln_men_cs1_polos&parentPage=family"
    }
    ,
    function (data)
    {

        document.getElementById ("output").innerHTML =  data;
    }
);

网站内容加载正常,但脚本没有加载,因为我在更改任何应该执行脚本的选项时遇到错误。

我尝试了不同的方法,但没有用。

如何实现也加载脚本。

编辑 看来我的问题不清楚。

问题是,给定 URL 的内容和脚本正在我的页面中加载。外部 URL 包含一些未执行的嵌入式脚本。

这是一个外部网站的例子

<html>
<body>
Hello
<script>
alert("This is some message"); 
</script>
</body>
</html>

现在如果我们直接在浏览器中运行此页面,它会显示文本“Hello”以及警告消息,但是当我通过上述方法(POST/Jquery)加载此文件时,它显示“Hello”但没有显示警报消息(意味着,不执行 javascript)。

请帮我执行那个脚本。

【问题讨论】:

  • 您是否在 php 脚本中回显 $html?
  • 您遇到什么错误?你能发布那个错误吗?

标签: php javascript jquery ajax


【解决方案1】:

将带有元素的 HTML 加载到页面中不是很稳定。这将无法跨浏览器工作,因为某些浏览器不会在外部页面中运行 onload(使用 ajax 获取)。

所以不要这样做,在你$.post的回调操作中运行你需要的javascript。

编辑 另见this

【讨论】:

    【解决方案2】:

    不知道为什么你的不工作,但试试这个,似乎工作完美:

    <?php 
    if($_SERVER['REQUEST_METHOD']=='POST' && $_POST['url']){
        header('Content-Type: text/html');
        echo file_get_contents($_POST['url']);
        die;
    }
    ?> 
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" charset="utf-8"></script>
    
    <script charset="utf-8" type="text/javascript">
    $(function() {
        $.post ("back.php",{
            url : "http://www.ralphlauren.com/product/index.jsp?productId=2130294&cp=1760781.1760809&ab=ln_men_cs1_polos&parentPage=family"
        },function (data){
            document.getElementById ("output").innerHTML =  data;
        });
    });
    </script>
    
    </head>
    <body>
    
    <div id="output"></div>
    
    </body>
    </html>
    

    【讨论】:

      【解决方案3】:

      错误可能由以下原因引起:

      • 可能是你忘记加载 jQuery 库了。

      • 您忘记将代码包装在准备好的 DOM 中,即。 $(function() { })

      • 如果您尝试从不同域检索数据,则应尝试使用jsonp 类型请求。

      【讨论】:

        【解决方案4】:

        你应该在执行时使用$(function() { })来加载js!

        【讨论】:

          猜你喜欢
          • 2011-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多