如何通过javascript和代理简单地从任何URL读取html


How to simply read html from any url via javascript and proxy?

这是我proxy.php文件:

$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url); // Avoid accessing the file system
echo file_get_contents($url); // You should probably use cURL. The concept is the same though

和我的reader.js

$(document).ready(function () {
    var url = 'http://localhost/taboo.blue-world.pl/admin/proxy.php?url=' + encodeURIComponent('http://www.blue-world.pl')
    $.ajax({
        url      : url,
        type     : 'GET',
        dataType : 'json'
    }).done(function(data) {
        console.log(data.results.result[1].category); // Do whatever you want here
    });
});

但它不打印任何东西。你能帮我解决吗?我不太擅长这个。

目前您正在尝试获取 JSON 响应。将dataType更改为html

dataType: 'html'

看起来您正在尝试以 JSON 形式获取 HTML 响应。

如果内容是 HTML,您应该将 ajax 调用转换为:

$.ajax({
    url      : url,
    type     : 'GET',
    dataType : 'html'
}).done(function(data) {
    console.log(data); // data contains the html as a text
});

在阅读器中使用任一dataType: 'html'.js(获取 HTML 数据)

在代理中echo(json_encode(file_get_contents($url)));.php(对于 JSON 数据)

尝试jQuery.parseJSON JSON 格式

 $.ajax({
        url      : url,
        type     : 'GET',
        dataType : 'json'
    }).done(function(data) {
        var data = jQuery.parseJSON(data);
        console.log(data.results.result[1].category); // Do whatever you want here
    });
    });