这里是PHP文档
如果我找不到纯客户端的方法,这里是我如何在Ajax调用中使用它。
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
有没有办法在客户端完成这个操作而不必将字符串通过ajax发送到服务器端?
这里是PHP文档
如果我找不到纯客户端的方法,这里是我如何在Ajax调用中使用它。
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
有没有办法在客户端完成这个操作而不必将字符串通过ajax发送到服务器端?
现在已经是2020年,一些现代方法越来越流行;
async function file_get_contents(uri, callback) {
let res = await fetch(uri),
ret = await res.text();
return callback ? callback(ret) : ret; // a Promise() actually.
}
file_get_contents("https://httpbin.org/get", console.log);
// or
file_get_contents("https://httpbin.org/get").then(ret => console.log(ret));
$.post('phppage.php', { url: url }, function(data) {
document.getElementById('somediv').innerHTML = data;
});
PHP 代码:
$url = $_POST['url'];
echo file_get_contents($url);
JavaScript无法直接从页面上获取数据。它可以调用本地的PHP脚本代表其自己获取数据,但是JavaScript(在浏览器中)无法直接做到这一点。
$.post("/localScript.php", { srcToGet: 'http://example.com' }, function(data){
/* From within here, data is whatever your local script sent back to us */
});
这个函数将会返回一个字符串形式的文件,就像PHP中的 file_get_contents()
函数一样。
function file_get_contents(uri, callback) {
fetch(uri).then(res => res.text()).then(text => callback(text));
}
然而,与 PHP 不同的是,JavaScript 会继续执行下一条语句,而不会等待数据返回。
<iframe>
元素中。但是这可能会导致某些布局问题(页面最终以固定大小的元素显示)。iframe
不是来自你的域的文档,则不行。 - Sampson<script>
var data = file_get_contents('Your URL');
</script>
我觉得这可能对您有用:
一个带有 "file-get-contents" 方法的 npm 软件包,适用于 node.js https://www.npmjs.com/package/file-get-contents
它是异步的,所以如果您正在使用express,则应该像这样使用
app.get('/', async (req, res)=>{
//paste here the code below
}
Example
const fileGetContents = require('file-get-contents'); // A File request try { let data = await fileGetContents('/tmp/foo/bar'); console.log(data); } catch (err) { console.log('Unable to load data from /tmp/foo/bar'); } // Or a HTTP(S) request fileGetContents('https://pokeapi.co/api/v2/pokemon/1/').then(json => { const pokemon = JSON.parse(json); console.log(`Name of first pokemon is ${pokemon.name}`); }).catch(err => { console.err(`Unable to get content from PokeAPI. Reason: ${err.message}`); });
<div id="svg">
</div>
<script>
function file_get_contents(uri, callback) {
fetch(uri).then(res => res.text()).then(text =>
{
var xmlSvg =text;
console.log(xmlSvg );
document.getElementById('svg').innerHTML = xmlSvg;
})
}
var uri ='You-urlllllllll-svg';
file_get_contents(uri);
</script>
function file_get_contents(filename) {
fetch(filename).then((resp) => resp.text()).then(function(data) {
document.getElementById("id").innerHTML = data;
});
}
file_get_contents("url");
<span id="id"></span>