2011-10-19 63 views
2

我正在嘗試使用javascript並使用xmlhttp讀取from http://search.yahooapis.com/ WebSearchService /V1/webSearch?appid=YahooDemo &query=persimmon&results=2。我發現了一個錯誤,因爲除非你的網站上search.yahooapis.com你可能遇到Same Origin Policy託管它無法讀取JavaScript 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> 
+0

有什麼確切的錯誤? –

+0

有錯誤是'失敗',其他部分警報(「失敗」)中的塊 – Noor

回答

1

這導致您的呼出請求與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