我使用下面的代码访问HTML页面
<html><head><title>jsonp test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head><body>
<script type="text/javascript">
$(document).ready(function() {
var url = "http://www.yahoo.com";
$.getJSON(url,null,function(data,status,xhr) {
alert(data+" "+status+" "+xhr);
});
});
</script>
</body></html>
但数据始终返回null 为什么呢?
更新了问题:
参考雅虎的方法 http://developer.yahoo.com/javascript/howto-proxy.html
php_proxy_simple.php
// Allowed hostname (api.local and api.travel are also possible here)
define ('HOSTNAME', 'http://www.google.com/');
//define ('HOSTNAME', 'http://search.yahooapis.com/');
// Get the REST call path from the AJAX application
// Is it a POST or a GET?
$path = ($_POST['yws_path']) ? $_POST['yws_path'] : $_GET['yws_path'];
$url = HOSTNAME.$path;
// Open the Curl session
$session = curl_init($url);
// If it's a POST, put the POST data in the body
if ($_POST['yws_path']) {
$postvars = '';
while ($element = current($_POST)) {
$postvars .= urlencode(key($_POST)).'='.urlencode($element).'&';
next($_POST);
}
curl_setopt ($session, CURLOPT_POST, true);
curl_setopt ($session, CURLOPT_POSTFIELDS, $postvars);
}
// Don't return HTTP headers. Do return the contents of the call
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Make the call
$xml = curl_exec($session);
// The web service returns XML. Set the Content-Type appropriately
header("Content-Type: text/xml");
echo $xml;
curl_close($session);
?>
我的代码调用web代理php_proxy_simple.php并获取google.com的html代码
<html>
<head>
<script type="text/javascript">
function load()
{
var path = '';
var url = 'http://www.mysite.com/php_proxy_simple.php?yws_path=' + encodeURIComponent(path);
var xhr = new XMLHttpRequest();
xhr.open('GET', url,true );
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 ){
alert ("length:"+xhr.responseText.length+xhr.responseText);
}
}
xhr.send();
}
</script>
</head>
<body onload="load()">
</body>
</html>
xhr.responseText.length始终为0,xhr.responseText返回null
答案 0 :(得分:1)
您无法使用getJSON请求跨域内容,您需要服务器上的代理才能请求内容。在您的代理使用jquery-ajax后,请检查http://developer.yahoo.com/javascript/howto-proxy.html。
$.ajax('/getpage', {
data:{pageurl:"http://www.yahoo.com"},
type:'POST'
}).done(function(resp){
console.log(resp.pagecontent);
});