0

我想在 javascript 中读取 URL 的内容。该 URL 不在我的域中,因此我需要一个可以跨域访问的中间层。我尝试使用 PHP 函数读取 URL 并使用 jquery 将结果返回给 javascript,但它不起作用。

这是我的试验:

我创建了一个名为“phpjs_test.php”的 php 文件

<?php
function get_data(){
  $url='http://asmary.dreameg.com/texttable.txt';
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  $content = curl_exec($ch);
  $content = htmlspecialchars($content);
  curl_close($ch);
  $content = nl2br($content);
  return $content;
}
?>

这是javascript代码:

<script>
        $(document).ready(function () {
            //httpQuery("http://asmary.dreameg.com/texttable.txt");
            getOutput();
        });

        function getRequest() {
            var req = false;
            try {
                // most browsers
                req = new XMLHttpRequest();
            } catch (e) {
                // IE
                try {
                    req = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                    // try an older version
                    try {
                        req = new ActiveXObject("Microsoft.XMLHTTP");
                    } catch (e) {
                        return false;
                    }
                }
            }
            return req;
        }

        function getOutput() {
            var ajax = getRequest();
            ajax.onreadystatechange = function() {
                if (ajax.readyState == 4) {
                    document.getElementById('output').innerHTML = ajax.responseText;
                }
            };
            ajax.open("GET", "phpjs_test.php", true);
            ajax.send(null);
        } 

我对 PHP 完全陌生,所以我什至不知道 PHP 函数是否正确。

4

2 回答 2

0

您应该只使用 jQuery ajax 方法而不是创建 XMLHTTPRequest,您不必费心为 IE 添加更多代码,而且您已经加载了 jQuery 库。此外,如果您在 PHP 文件中将标头设置为 Allow-Origin-Access 并指定您请求的其他域,那么您可以发出 AJAX 请求并获得响应,否则它将不返回任何内容或在您的开发工具网络选项卡中返回将显示 403 - 禁止。

访问控制允许来源语法

于 2013-02-03T08:30:43.117 回答
0

将 PHP 文件更改为:

<?php
$url='http://asmary.dreameg.com/texttable.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
$content = explode('~',$content);

foreach($content as $c)
{
    $records[] = explode('|',$c);
}
$content = json_encode($records);
echo $content;
?>

Javascript 会收到这样的 json 数组

[["1","name1","10","city1"],["2","name2","20","city2"],["3","name3","30","city3"],["4","name4","40","city4"],["5","name5","50","city5"],["6","name6","60","city6"],["7","name7","7","city7"],["8","name8","80","city8"],["9","name9","90","city9"],["10","name10","100","city10"],["11","name11","11","city11"],["12","name12","12","city12"],["13","name13","13","city13"],["14","name14","14","city14"],["15","name15","15","city15"],["16","name16","16","city16"],["17","name17","17","city17"],["18","name18","18","city18"],["19","name19","19","city19"],["20","name20","20","city20"],[""]]
于 2013-02-03T09:22:53.917 回答