【问题标题】:Javascript src from file depending on domain name来自文件的 Javascript src 取决于域名
【发布时间】:2013-01-10 18:48:46
【问题描述】:

我有文件http://host1.com/links.txt

links.txt 包含:

com http://host1.com/1.jpg
info http://host1.com/2.jpg
org http://host1.com/3.jpg

我需要根据主机域从该文件中放入此代码 src 链接。

a=document.getElementsByTagName('body')[0];
st='iframe';
r=st;
b=document.createElement(r);
b.src=**Here from links.txt**
b.width=300;b.height=300;b.marginHeight=10;b.marginWidth=10;b.frameborder=10;b.align='left';
a.appendChild(b);

例如,我有 3 个其他网站

1. http://site1.com
2. http://site2.info
3. http://site3.org

在每个站点的 index.php 中,我需要放入 iframe 代码,并在以下源代码中:

http://site1.com/index.php 我必须有 b.src=http://host1.com/1.jpg

http://site1.info/index.php 我必须有 b.src=http://host1.com/2.jpg

http://site1.org/index.php 我必须有 b.src=http://host1.com/3.jpg

我该怎么做?

【问题讨论】:

    标签: php javascript iframe


    【解决方案1】:

    如果您可以控制links.txt 并且可以将其更改为JSON,则可以使用JSONP 来读取它。

    您可以使用window.location.hostname获取主机名。

    links.php

    <?php header('content-type: application/json; charset=utf-8'); ?>
    
    (function(){
        var data = {
            com: 'http://host1.com/1.jpg',
            info: 'http://host1.com/2.jpg',
            org: 'http://host1.com/3.jpg'
        };
    
        <?php echo $_GET['callback']; ?>(data);
    })();
    

    javascript

    $(function(){
        $.ajax({
           type: 'GET',
            url: 'http://mysite.com/links.php?callback=?',
            async: false,
            jsonpCallback: 'jsonpCallback',
            contentType: "application/json",
            dataType: 'jsonp',
            success: function(json) {
               alert(json.info);
               alert(json.com);
               alert(json.org);
            }
        });
    });
    

    【讨论】:

    • 我只能使用javascript或PHP
    • JSONP/jQuery javascript
    • 我更新了我的示例,以便更好地了解它的工作原理。
    猜你喜欢
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多