我想在javascript中阅读网址的内容。该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函数是否正确。
答案 0 :(得分:0)
你应该只使用jQuery ajax方法而不是创建XMLHTTPRequest,你不必费心为IE添加更多代码,而且你已经加载了jQuery库。此外,如果您在PHP文件中将标头设置为Allow-Origin-Access并指定您要求的其他域,那么您可以发出AJAX请求并获得响应,否则它将不返回任何内容或在您的开发工具网络选项卡中将显示403 - 禁止。
答案 1 :(得分: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"],[""]]