-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に記載されている yahoo の方法を参照してください。

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 を返します

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 に答える