【问题标题】:Calling an external html file using JSONP and PHP使用 JSONP 和 PHP 调用外部 html 文件
【发布时间】:2014-10-04 02:25:40
【问题描述】:

对于这里的许多人来说,这个问题可能有点模糊,但我对该主题的了解也很模糊,尽管进行了一些搜索,但我无法在网上找到任何地方,其中包含有关如何进行的明确说明这样做虽然(在我看来)它可能应该是更简单的跨域 JSONP 操作之一。

我会解释我想要做什么。我正在尝试使用 JSONP 和 PHP 脚本在外部服务器上检索 HTML 文件的内容。我可以访问服务器 - 我的 PHP 脚本如下:

    <?php
    $callback = '';
    if (isset($_GET['callback']))
    {
    $callback = filter_var($_GET['callback'], FILTER_SANITIZE_STRING);
    }
    $html = include($callback);
    echo $callback . '('.json_encode($html).');';
    ?>

使用它似乎当我键入www.myurl.com/myscript.php?callback=filename.html 时,会显示正确的文件(尽管由于某种原因,?callback 在地址中重复,并且文件名附加到显示的输出的末尾。 ..

我为我的 HTML 文件尝试了几个不同的脚本,但目前有以下...

    function request_jsonp(){
    var script = document.createElement('script');
    var url = 'http://www.myurl.com/myscript.php?callback=filename.html';
    script.setAttribute('src', url);
    document.getElementsByTagName('head')[0].appendChild(script);
    }

现在显然这不起作用,因为 PHP 脚本的输出不是任何类型的工作函数,但我不确定制作它的最佳方法。我想以某种方式将输出包装成这样:

    function DisplayOutput() {
        document.getElementById('output').innerHTML = ...external HTML goes here!... ;
    }

...但目前我真的不确定最好的方法。

非常感谢任何帮助。

【问题讨论】:

    标签: javascript php html cross-domain jsonp


    【解决方案1】:

    callback 需要是回调函数的名称。每次调用该函数时,您都应该生成一个唯一的。

    您应该使用第二个不同的查询字符串变量来确定要获取的 URI。

    var jsonp_counter = 0;
    
    function request_jsonp(url, callback){
        jsonp_counter++;
        var callback_name = "jsonp_function_" + jsonp_counter;
        window[callback_name] = callback;
    
        var jsonp_url = 'http://www.myurl.com/myscript.php" +
                  "?callback=" + encodeURIComponent(callback_name) +
                  "&url=" + encodeURIComponent(url);
    
        var script = document.createElement('script');
        script.setAttribute('src', url);
        document.getElementsByTagName('head')[0].appendChild(script);
    }
    
    request_jsonp("filename.html", function (data) {
         do_something_with(data);
    });
    

    【讨论】:

    • 也许(可能)我错过了一些明显的东西,但这似乎只是试图在本地检索文件...... Javascript 控制台报告错误“找不到文件”......
    猜你喜欢
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    • 2016-11-29
    • 2019-02-10
    • 1970-01-01
    • 2010-10-18
    相关资源
    最近更新 更多