How to make an AJAX call from inside Silverlight

Here is a little snippet that will let you make a remote AJAX call from inside Silverlight – the only catch is that you will get a “security warning” dialog for making a crossdomain call

ScriptObjectCollection scriptCollection = HtmlPage.Document.GetElementsByTagName("head");
HtmlElement head = (HtmlElement)scriptCollection[0];

HtmlElement script = HtmlPage.Document.GetElementById("dataAccess_js");
if (script == null)
{
	script = HtmlPage.Document.CreateElement("script");
	script.SetAttribute("type", "text/javascript");
	script.Id = "dataAccess_js";

	StringBuilder sbScript = new StringBuilder();

	sbScript.AppendLine("function createXMLHttpRequest() { var httprequest = false; if (window.XMLHttpRequest) { httprequest = new XMLHttpRequest(); if (httprequest.overrideMimeType) httprequest.overrideMimeType("text/xml"); } else if (window.ActiveXObject) {  try { httprequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { httprequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } return httprequest; }");
	sbScript.AppendLine("function retrieveContent(url) { var request = createXMLHttpRequest(); request.open("GET", url, false); request.send(null); if (request.status == 200) { var text = request.responseText; return text; } else { alert("Error loading " + url); } }");

	script.SetProperty("text", sbScript);

	head.AppendChild(script);
}

var result = HtmlPage.Window.Invoke("retrieveContent", sURL);