views:

337

answers:

3

I'm trying to create a bookmarklet that will start off an AJAX call to an aspx page I've written.

The code tests out perfectly when I place the javascript in a static html page, but when I try and call it off from a bookmarklet, the code will just hang at the xmlHttp.open("GET", url, true) part.

The code of the bookmarklet is basically this (found on several examples on the web):

javascript:(function(){
  var s,
  d=document,
  a=function(o){ d.body.appendChild(o) };
  s=d.createElement('script');
  s.type='text/javascript';
  s.src='http://localhost/squirt/sq.js';
  a(s)
})();

This adds the contents of sq.js (the ajax call + some other processing) to whatever page the browser is currently at, and then calls off the ajax to my aspx page.

I'm using ASP 2.0 (with VS2008) and IIS 7. So far I've just been testing it on my home network.

I assume there must be some sort of permissions issue with the ajax call from an outside page, since, like I said, everything works fine from a static page. Is this an IIS setting I need to change to allow the call, or am I doing something completely wrong?

+1  A: 

The XMLHttpRequest object is subject to a Same Origin Policy.
This is why the script your bookmarklet is loading can't use an XHR to get data from your server unless it's embedded in a page from your server.
Script added by dynamically adding a script tag will work though, as you can tell - your bookmarklet can load script from a different origin.
So there's your answer. Don't use an XMLHttpRequest object: dynamically load your script in the same way the bookmarklet does.
This is how JSONP works (actually there's a bit more to JSONP but that's how it gets around the SOP)

Actually, why not just use JSONP

meouw
Thanks, got it working with JSON and dynamic scripts! I had never heard of JSON before, good stuff.
Luke
Glad it worked for you. Just to avoid confusion: JSON != JSONP. JSON is a data exchange format, JSONP refers to a way of loading Padded/Prefixed JSON data from a different domain. :)
meouw
A: 

Injecting JavaScript code on the page still has the same permission issues as code that is there normally. You can not make an Ajax call to a different domain. So if you are calling localhost from example.com, it is not going to work.

You might want to look at returning JSON from your service and make JSON calls with a script tag.

Eric

epascarello
A: 

The code you're using there is rather ugly, I would suggest using something like this that I built: http://sktrdie.org/getScript.js

It works like this:

getScript("http://anotherdomain.com/something", function(data) {
    alert(data); // the request is complete
});

On the http://anotherdomain.com/something it would have to return something like this, given you're using PHP:

echo $_GET["jsonp"]."('Testing data, you can put anything in here');";

Be sure to read about JSONP.

Luca Matteis