JavaScript xmlhttp читается из фида - PullRequest
2 голосов
/ 19 октября 2011

Я пытаюсь использовать JavaScript и читать из http://search.yahooapis.com/ WebSearchService / V1 / webSearch? Appid = YahooDemo & query = persimmon & results = 2 с использованием xmlhttp.Я получаю сообщение об ошибке, потому что он не может прочитать

<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 Ответ

1 голос
/ 19 октября 2011

Если ваш веб-сайт не размещен на search.yahooapis.com, вы, вероятно, сталкиваетесь с той же политикой происхождения .

В результате ваш исходящий запрос возвращается с кодом состояния 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


Это также выглядит как эта служба была закрыта :

enter image description here

...