views:

78

answers:

2

Hi!

I'm looking for a very small (one liner) ajax javascript library to add on the first line of a small script to make some requests.

I already tried: http://www.openjs.com/scripts/jx/ http://code.google.com/p/microajax/

But they do not work at all. Alternatives?

+1  A: 

Well...... jQuery is probably bigger than what you want, but it's arguably still a very good option. It's well documented, well supported, and if you use the CDN link

http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js

it is even very likely to be present and cached on the client's machine already.

Pekka
Google CDN: http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
Radu
@Radu cheers, that URL was what I meant.
Pekka
Thanks but I only wanted a little snippet. I use jQuery for all my javascript-related work but for this time I needed something very small.
Tom
@Tom then @Ryan's approach should be perfect - it's as small as it'll get.
Pekka
+4  A: 

Here you go, pretty simple:

function createXHR()
{
    var xhr;
    if (window.ActiveXObject)
    {
        try
        {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e)
        {
            alert(e.message);
            xhr = null;
        }
    }
    else
    {
        xhr = new XMLHttpRequest();
    }

    return xhr;
}

Documentation is here

Example:

var xhr = createXHR();
xhr.onreadystatechange = function()
{
    if (xhr.readyState === 4)
    {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'test.txt', true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send()

Update:

In order to do cross-domain scripting, you'll either have to call out to a local server-side proxy (which reads and echo's the remote data), or, if your remote service returns JSON, use this method:

var s = document.createElement('script')
s.src = 'remotewebservice.json';
document.body.appendChild(s);

Since JSON is essentially a JavaScript object or array, this is a valid source. You theoretically should then be able to call the remote service directly. I haven't tested this, but it seems to be an accepted practice:

Reference: Calling Cross Domain Web Services in AJAX

Ryan Kinal
Exactly what I wanted. Thanks!
Tom
Always glad to help!
Ryan Kinal
Oh but now what I forgot was: it should be cross-domain :O
Tom
Ooh, that's a rough one. [researches]
Ryan Kinal
@Tom I'd say that's worth a question of its own.
Pekka
Updated with an untested answer :-D
Ryan Kinal
@Ryan nice work, and even more minimalistic than a normal Ajax call :)
Pekka
I think you have to do both, actually. Since the JSON object isn't assigned to any variable, there's no good way to reference it. It sucks, but that's the price you pay for subverting the system ;-)
Ryan Kinal