-1

我使用下面的代码访问 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);

?>

我的代码调用网络代理 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

4

1 回答 1

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);
});
于 2013-10-20T06:48:39.863 回答