bing search api ajax does not work
I want to use the Bing's search api with javascript. Actually, I want the user to write something and query Bing in order to get just images.
so, I tried it using ajax. If I try the url http://api.search.live.net/xml.aspx?Appid=[YOURAPIKEY]&sources=image&query=home directly (with the browser) I do get an xml document.
but if I use XMLHttpRequest it does not work.
<html>
<body>
<script>
var xhr = new XMLHttpRequest();
var url="http://api.search.live.net/xml.aspx?Appid=[YOURAPIKEY]&sources=image&query=home"
xhr.open("GET", url, true );
xhr.onreadystatechange=function(){
/*if( xhr.readyState == 4 && xhr.status == 200) {
document.write( xhr.responseText );
}*/
alert( "state: "+xhr.readyState +" status: "+xhr.status +" statusText: "+xhr.statusText +" respText: "+xhr.responseText);
};
xhr.send(null);
</script>
</body>
</html&开发者_如何转开发gt;
Questions: 1) why does the code from above does not work? 2) any other way to do this without XMLHttpRequest?
thanks.
btw. I'm just interested in fix this for Firefox and without external libraries (jquery and so on).
You can't do XHR cross-domain. You need JSONP.
<script type="text/javascript">
function processBingImages(resp){
...
};
</script>
<script type="text/javascript" src="http://api.search.live.net/json.aspx?Appid=[YOURAPIKEY]&sources=image&query=home&JsonType=callback&JsonCallback=processBingImages"></script>
You can make this dynamic (using createElement("script")
, etc.) if needed. See this answer.
By using JsonType=callback
we specify JSONP, and the JsonCallback
parameter specifies that the response should call processBingImages
. The MSDN documentation has details.
精彩评论