views:

149

answers:

1

Hi guys,

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]&amp;sources=image&amp;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>

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).

A: 

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]&amp;sources=image&amp;query=home&amp;JsonType=callback&amp;JsonCallback=processBingImages"&gt;&lt;/script&gt;

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.

Matthew Flaschen
You can't do XHR cross-domain. You need JSONP <--- I guess, this will happend with Bing or Google or Yahoo apis, right?
jhon
Yes, you'll have the same problem with any XHR to a different domain. I know Google has specific services to allow you to achieve this without an XHR; perhaps Bing has something similar.
dmazzoni