使用主机名从地址运行文件

时间:2014-11-22 04:00:55

标签: javascript jquery

有一个我试图用于Blogger的脚本。当您将域URL输入src时,它会起作用,但我试图找到一种方法来使用主机名来插入域。

原始剧本:

<script type="text/javascript" src="http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=INSERT-YOUR-URL-HERE&amp;ShowHowMany=5&amp;_id=390e906036f48772b2ed4b5d837af4cd&amp;_callback=getYpipePP&amp;_render=json" />

我试过了:

<script type="text/javascript">
    var excuteTopCommentators = "http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'+window.location.hostname+'&amp;ShowHowMany=5&amp;_id=390e906036f48772b2ed4b5d837af4cd&amp;_callback=getYpipePP&amp;_render=json"
    return excuteTopCommentators
</script>

我也尝试过document.write:

<script type="text/javascript">
    document.write('<script type="text/javascript" src="http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'+window.location.hostname+'&amp;ShowHowMany=5&amp;_id=390e906036f48772b2ed4b5d837af4cd&amp;_callback=getYpipePP&amp;_render=json"></script>');
</script>

这两种尝试似乎都没有效果。关于如何在不手动将域URL插入脚本src中的任何想法?

3 个答案:

答案 0 :(得分:0)

问题可能是您获得了脚本,但它永远不会被执行。

也许尝试jQuery的getScript http://api.jquery.com/jquery.getscript/

function getIt() {
  return $.getScript('http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'+window.location.hostname+'&amp;ShowHowMany=5&amp;_id=390e906036f48772b2ed4b5d837af4cd&amp;_callback=getYpipePP&amp;_render=json');
}

答案 1 :(得分:0)

你的第二个选择看起来不错:

<script type="text/javascript">
    document.write('<script type="text/javascript" src="http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'+window.location.hostname+'&amp;ShowHowMany=5&amp;_id=390e906036f48772b2ed4b5d837af4cd&amp;_callback=getYpipePP&amp;_render=json"></script>');
</script>

脚本已下载但不执行任何操作。 这是因为它是JSONP,而不是脚本

所以,你需要一个回调函数来使它工作:(注意这是数据,而不是代码)

<script type="text/javascript">
    // JSONP Callback
    function getYpipePP(data) {
        alert(JSON.stringify(data));
    }

    document.write('<script type="text/javascript" src="http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'+window.location.hostname+'&amp;ShowHowMany=5&amp;_id=390e906036f48772b2ed4b5d837af4cd&amp;_callback=getYpipePP&amp;_render=json"></script>');

</script>

http://plnkr.co/edit/HhYZtH09EcdPZbwS9rfq?p=preview

查看查询,说出_callback=getYpipePP_render=json

相关: What is JSONP all about?

答案 2 :(得分:0)

试试这个(你遇到的问题是结束“脚本”标签):

<script type="text/javascript">
        document.write('<script language="javascript" src="http://pipes.yahoo.com/pipes/pipe.run?YourBlogUrl=http://'
                     + window.location.hostname
                     + '&amp;ShowHowMany=5&amp;_id=390e906036f48772b2ed4b5d837af4cd&amp;_callback=getYpipePP&amp;_render=json" type="text/javascript"><\/script>')
    </script>