如何使用JSONP显示纯HTML

How to display pure HTML using JSONP

本文关键字:HTML 显示 JSONP 何使用      更新时间:2023-09-26

我们试图避免使用iframe,而是使用基于javascript、jquery、jsonp和php的web小部件来显示跨域html网站的内容。我们希望在小部件中显示完整的页面,但从我们阅读的所有教程中,都提到我们需要提供JSON数据类型,以便跨域JSONP工作。

以下是我们尝试的

主要JS

function render() {
  jQuery.getJSON(serverFQDN + '/widget.php?callback=?', {
  install_url: window.location.href
  }, serverResponse);
}
function serverResponse(data) {    
  jQuery(container).html(data.html);
}

小工具.php

<?php echo $_GET['callback'] ?>({
   "html": "<?php echo 'hello'; ?>"
});

我们能够显示简单的html实体,如-

<?php   echo $_GET['callback'] ?>({"html": "<li>TEST</li>"

});

但不是整页,即

<?php
$url = "http://localhost/page.html";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);
$output = json_encode($output);
echo $_GET['callback'] ?>({"html": "<?php echo $output; ?>"

});

您应该使用cURL或Firebug进行检查,但我认为您对HTML进行了双重JSON编码。

也不清楚你为什么写:

echo $_GET['callback'] ?>({"html": "<?php echo $output; ?>" });

而不是

echo $_GET['callback'] ?>({"html": $output });

EDIT:没关系,我有它。您的JSON编码只是Javascript编码——但您有一组额外的引号!

如果$output是"<li>TEST</li>",则您正在创建的文件是

 jsonpCallback({"html" : ""<li>TEST</li>""});

嗯,我想。就像我说的,使用cURL或Firebug来检查实际输出。