从源读取的JavaScript xmlhttp

时间:2011-10-19 18:19:02

标签: javascript xml feed

我正在尝试使用javascript并使用xmlhttp阅读from http://search.yahooapis.com/ WebSearchService /V1/webSearch?appid=YahooDemo &query=persimmon&results=2。我收到错误,因为它无法读取

<script type="text/javascript">
       url="http://search.yahooapis.com/ WebSearchService /V1/webSearch?appid=YahooDemo &query=persimmon&results=2";
       var xmlhttp = null;
       if (window.XMLHttpRequest) 
       {
          xmlhttp = new XMLHttpRequest();
          if ( typeof xmlhttp.overrideMimeType != 'undefined') 
          {
             xmlhttp.overrideMimeType('text/xml');
          }
       } 
       else if (window.ActiveXObject) 
       {
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       } 
       else 
       {
          alert('Perhaps your browser does not support xmlhttprequests?');
       }

       xmlhttp.open('GET', url, true);
       xmlhttp.send(null);
       xmlhttp.onreadystatechange = function() 
       {
           if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
           {
            alert("success");
           }
           else 
           {
            alert("failure");
           }
      };
</script>

1 个答案:

答案 0 :(得分:1)

除非您的网站托管在search.yahooapis.com,否则您可能会遇到Same Origin Policy

这导致您的传出请求返回404状态代码:

enter image description here

您应该使用JSONP代替XMLHttpRequest

<!DOCTYPE html>
<html>
 <head>
     <title>JavaScript file download</title>
<script type="text/javascript">
     function yahooApi(resp) {
         var scriptEl = document.getElementById("yahooApiJsonP");
         scriptEl.parentNode.removeChild(scriptEl);
         console.log(resp);
     }

     window.onload = function() {
         var scriptEl = document.createElement("script");
         scriptEl.id = "yahooApiJsonP";
         scriptEl.src = "http://search.yahooapis.com/WebSearchService/V1/webSearch?output=json&callback=yahooApi&appid=YahooDemo&query=persimmon&results=2";
         document.body.appendChild(scriptEl);
     };
</script>
 </head>
 <body>
    <p>This is a test</p>
 </body>
</html>

这将发送请求,该请求将返回200 OK状态:enter image description here


它看起来也像this service has been shut down

enter image description here