有没有JavaScript方法来做file_get_contents()?

2022-08-30 21:59:32

这是 PHP 文档

以下是我在Ajax调用中如何使用它,如果我没有找到一个纯客户端方法来做到这一点。

$homepage = file_get_contents('http://www.example.com/');
echo $homepage;

有没有办法做这个客户端,这样我就不必ajaxing字符串了?


答案 1

你可以做

JS 代码:

$.post('phppage.php', { url: url }, function(data) {
    document.getElementById('somediv').innerHTML = data;        
});

PHP 代码:

$url = $_POST['url'];
echo file_get_contents($url);

这将为您提供URL的内容。


答案 2

这是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));