0

こんにちは、Google Weather から xml を取得したい

var xmlhttp;

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp= new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

 xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);

xmlhttp.send(null);

xmlDoc=xmlhttp.responseXML;

うまくいきません。ありがとう

4

3 に答える 3

3

XMLHttpRequest is asynchronous. You need to use a callback. If you don't want to use a full-fledged library, I recommend using Quirksmode's XHR wrapper:

function callback(xhr)
{
    xmlDoc = xhr.responseXML;
    // further XML processing here
}

sendRequest('http://www.google.com/ig/api?weather=london&hl=en', callback);

If you absolutely insist on implementing this yourself:

// callback is the same as above

var xmlhttp;

if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();
}
else
{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);

xmlhttp.onreadystatechange = function ()
{
    if (xmlhttp.readyState != 4) return;
    if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
    callback(xmlhttp);
};

xmlhttp.send(null);

Edit

As @remi commented:

I think you'll get a cross domain access exception : you can't make an ajax request to an other domain than your page's. no ?

Which is (for the most part) correct. You'll need to use a server-side proxy, or whatever API that Google provides, instead of a regular XHR.

于 2011-06-20T15:51:58.990 に答える
-1

クロスドメインリクエストであるために、JavaScriptを介してこれを行うことはできません。これはサーバー側で行う必要があります。

PHPでは、CURLを使用します。

あなたがやろうとしていることは、Javascriptではできません。

于 2011-06-20T17:15:12.913 に答える
-1

ここにコードがあります:

<html>
<body>

<script type="text/javascript">

var xmlhttp;
var xmlDoc;
function callback(xhr)
{
    xmlDoc = xhr.responseXML;
    // further XML processing here
}


if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();
}
else
{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.open("GET", "http://www.google.com/ig/api?weather=london&hl=en", true);
xmlhttp.onreadystatechange = function ()
{
    if (xmlhttp.readyState != 4) return;
    if (xmlhttp.status != 200 && xmlhttp.status != 304) return;
    callback(xmlhttp);
};

xmlhttp.send(null);



alert(xmlDoc);

</script>

</body>
</html>

エラーは返されませんが、アラートは未定義を返します。

于 2011-06-21T07:06:20.097 に答える