使用JSONP和PHP调用外部html文件


Calling an external html file using JSONP and PHP

对于这里的许多人来说,这个问题可能有点模糊,但我对这个主题的了解也很模糊,尽管进行了一些搜索,但我无法在网上找到关于如何做到这一点的明确说明,尽管(在我看来)它应该是一个更简单的跨域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!... ;
    }

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

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);
});