How to make an AJAX call from inside Silverlight

by Shawn November 17, 2009 08:05

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

Tags:

Scripting

Comments

8/28/2010 5:56:14 PM #

Holly Kopischke

are you using wp for this blog?

Holly Kopischke United States

8/28/2010 8:45:54 PM #

Dusty Lawrie

do you have an rss feed? I want to add it to my reader but I can't find it...

Dusty Lawrie United States

8/29/2010 1:16:55 AM #

seduction affiliates

hey, with so many comments you should add an affiliate program to your blog and make some money...

seduction affiliates United States

8/31/2010 4:39:28 PM #

dating blog

good work! keep posting more. I have a dating blog too but it's not so popular like yours..

dating blog United States

9/3/2010 4:09:08 AM #

gifts

try to change your template, there are some great ones...

gifts United States

9/3/2010 6:49:55 PM #

seduction

do you have a xml feed for your blog?

seduction United States

9/4/2010 11:25:33 PM #

dating

how old is this post?

dating United States

9/5/2010 7:10:21 AM #

ETF

do you have a different blog where you post more often?

ETF United States

9/7/2010 7:58:29 AM #

stocks trading

nice blog but it deserve a better theme...

stocks trading United States

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.6.1.0
Theme by Mads Kristensen | Modified by Mooglegiant